54 &55list容器的数据存取/反转和排序

#include<iostream>
#include<deque>
#include<vector>
#include<stack>
#include<algorithm>
#include<Queue>
#include<ctime>
#include<list>
using namespace std;
//list容器的数据存取



void printList(const list<int>&L)
{
	for (list<int>::const_iterator it = L.begin(); it != L.end(); it++)
	{
		cout << *it << " ";

	}
	cout << endl;
}
void test01()
{
	//创建list容器
	list<int>L1;
	//添加数据
	//尾插
	L1.push_back(10);
	L1.push_back(20);
	L1.push_back(30);
	L1.push_back(40);
	//L1.[0]  不可以用[]访问list中的元素
	//L1.at(0); 不可以用at访问list中的元素
	//原因: list的本质是链表 不使用连续性空间存储数据,迭代器也不支持随机访问
	cout << "第一个元素是:" << L1.front()<<endl;
	cout << "最后一个元素是:" << L1.back()<<endl;


	//验证迭代器是不支持随机访问的
	list<int>::iterator it = L1.begin();
	//it = it + 1;  不持支随机跳跃访问
	it++;//支持双向
	it--;


	
	
}
//交换
void test02()
{
	
}
int main()
{
	test01();
	//test02();
	system("pause");
	return 0;
}

#include<iostream>
#include<deque>
#include<vector>
#include<stack>
#include<algorithm>
#include<Queue>
#include<ctime>
#include<list>
using namespace std;
//list容器的反转和排序


void printList(const list<int>&L)
{
	for (list<int>::const_iterator it = L.begin(); it != L.end(); it++)
	{
		cout << *it << " ";

	}
	cout << endl;
}
void test01()//反转
{
	//创建list容器
	list<int>L1;
	//添加数据
	L1.push_back(20);
	L1.push_back(10);
	L1.push_back(60);
	L1.push_back(40);
	cout << "反转前:" << endl;
	printList(L1);

	L1.reverse();
	cout << "反转后:" << endl;
	printList(L1);
}

bool myCompare(int v1,int v2)
{   //降序 就让第一个数大于第二个数
	return v1 > v2;

}
//排序
void test02()
{
	//创建list容器
	list<int>L1;
	//添加数据
	L1.push_back(20);
	L1.push_back(10);
	L1.push_back(60);
	L1.push_back(40);
	cout << "排序前:" << endl;
	printList(L1);


	//所有不支持随机迭代器的容器,不可以用标准算法
	// 不支持随机访问迭代器的容器,内部会提供对应的一些算法
	//sort(L1.begin(), L1.end());
	
	L1.sort();   //默认排序规则 从小到大 升序
	cout << "升序排序后:" << endl;
	printList(L1);

	cout << "降序排序后:" << endl;
	L1.sort(myCompare);
	printList(L1);



}
int main()
{
	test01();
	test02();
	system("pause");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值