C++STLlist容器数据存取
功能描述:
对list容器中数据进行存取
函数原型:
front(); //返回第一个元素
back(); //返回最后一个元素
代码示例:
#include<iostream>
#include<list>
using namespace std;
void test01()
{
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--;
//it=it+1; //不支持随机访问
}
int main()
{
test01();
return 0;
}
总结:
*
list容器不可以通过[]或者at方式访问数据
返回第一个元素–front
返回最后一个元素–back
list反转排序
功能描述:
将容器中的元素反转,以及将容器中的数据进行排序
函数排序:
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 test01()
{
list<int>L1;
L1.push_back(10);
L1.push_back(20);
L1.push_back(40);
L1.push_back(50);
L1.push_back(30);
cout << "反转前: " << endl;
printList(L1);
//反转后
L1.reverse();
cout << "反转后:" << endl;
printList(L1);
}
bool myCompare(int v1,int v2)
{
return v1 > v2;
}
//排序
void test02()
{
list<int>L1;
L1.push_back(10);
L1.push_back(20);
L1.push_back(40);
L1.push_back(50);
L1.push_back(30);
cout << "排序前: " << endl;
printList(L1);
//所有不支持随机访问的迭代器的容器,不可以用标准算法
//不支持随机访问迭代器的容器,内部会提供对应一些算法
//sort(L1.begin(), L1.end());
L1.sort();//默认排序规则 从大到小,升序排序
cout << "排序后: " << endl;
printList(L1);
L1.sort(myCompare);
printList(L1);
}
int main()
{
//test01();
test02();
return 0;
}
总结:
反转—reverse
排序—sort(成员函数)