list反转和排序

  1. 功能:将容器中的元素反转和对其中的数据进行排序
  2. 函数原型
  • 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;
     } 

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值