#include<iostream>
#include<algorithm>
#include<list>
#include<string>
using namespace std;
//list反转和排序:
//list打印函数:
void printList(const list<int>&L)
{
for (list<int>::const_iterator it = L.begin(); it != L.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
//排序回调函数:
bool myCompare(int val1, int val2)
{
return val1 > val2;
}
void test01()
{
list<int> L;
L.push_back(10);
L.push_back(20);
L.push_back(30);
L.push_back(40);
L.reverse();
printList(L);
//但是,所以不支持随机访问的迭代器,都不能使用系统提供的sort算法;
//如果不支持系统提供的sort算法,那么这个类内部会提供相应的sort算法;
//例如:sort(L.begin(),L.end());不能通过编译;
L.sort();
//从小到大排序;
printList(L);
//要从大到小,使用回调函数:
//不能写小括号,小括号是函数的调用:
L.sort(myCompare);
printList(L);
}
//自定义数据类型:
class Person
{
public:
Person(string name ,int age):m_Name(name),m_Age(age){}
string m_Name;
int m_Age;
};
void printList_2(const list<Person>&l)
{
for (list<Person>::const_iterator it = l.begin(); it != l.end(); it++) {
cout << "名字是:"<<(*it).m_Name<<" 年龄是:" << (*it).m_Age << endl;
}
}
//自定义类型的回调函数:
bool myCompare_2(Person &p1, Person & p2)
{
if (p1.m_Age < p2.m_Age) {
return true;
}
else
return false;
}
void test02()
{
list<Person> L1;
Person p1("sadsad", 10);
Person p2("asfaf", 20);
Person p3("zxcasd", 40);
Person p4("ertret", 50);
Person p5("dfgdfg", 10);
L1.push_back(p1);
L1.push_back(p2);
L1.push_back(p3);
L1.push_back(p4);
L1.push_back(p5);
printList_2(L1);
//按年龄进行排序:
L1.sort(myCompare_2);
cout << "按年龄进行排序:" << endl;
printList_2(L1);
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
STL-----list的反转和排序
猜你喜欢
转载自blog.csdn.net/XUCHEN1230/article/details/86545041
今日推荐
周排行