- 功能:将容器中的元素反转和对其中的数据进行排序
- 函数原型
- reverse(); // 反转链表
- sort(); // 链表排序
#include<iostream> #include<list> #include<algorithm> using namespace std; void printlist(const list<int> &L) { for(list<int>::const_iterator it=L.begin();it!=L.end();it++) { cout<<*it<<" "; } cout<<endl; } void test1() { list<int> L; L.push_back(1); L.push_back(2); L.push_back(3); L.push_back(4); L.push_back(5); printlist(L); // 反转前 1 2 3 4 5 L.reverse(); printlist(L); // 反转后 5 4 3 2 1 } bool mycompare(int a, int b) { return a>b; } void test2() { list<int> L1; L1.push_back(1); L1.push_back(6); L1.push_back(3); L1.push_back(9); L1.push_back(2); cout<<"排序前: "<<endl; printlist(L1); // 1 6 3 9 2 //所有不支持随机访问迭代器的容器,不可以用标准算法,所以sort(L1.begin() , L1.end() ) 不可用 //不支持随机访问迭代器的容器, 内部会提供一些对应算法 cout<<"升序排序后: "<<endl; L1.sort(); //默认升序 printlist(L1); // 1 2 3 6 9 cout<<"降序排序后: "<<endl; L1.sort(mycompare); //降序 printlist(L1); // 9 6 3 2 1 } int main() { test1(); test2(); return 0; }