C++ STL,list,来了!
今天给小伙伴们带来的是C++模块中的list,该模板是双端链表的模板,接下来通过实际代码的演练,帮助大家一起来掌握list对象的常见方法!肝!
代码如下:
#include<iostream>
#include<list>
using namespace std;
int main() {
//C++中的list实际上是一个双端链表且为一个循环链表
//本程序主要演示list常使用的方法
//双端链表实例化
list<int>list1;
//使用size方法读取list对象元素
int size1 = list1.size();//读取list1默认元素数量
cout << "默认条件下list初始化元素数目为:" << size1 << endl;
//使用
for (int i = 0; i < 5; i++) {
list1.push_front(i);//使用push_front方法从list对象前面读入数据
list1.push_back(2 * i + 1);//使用push_back从list对象后面读入数据
}
//利用迭代器实现list元素访问
cout << "读入的数据序列为:";
for (list<int>::iterator iter1 = list1.begin(); iter1 != list1.end();iter1++) {
cout << *iter1 << " ";
}
//读取现在的元素数目
int size2 = list1.size();
cout << "添加元素后list1中元素数目为:" << size2 << endl;
//使用front和back方法读取list对象中的元素
int Front = list1.front();//读取list1中第一个元素
int Back = list1.back();//读取list1中最后一个元素
cout << "第一个元素为:" << Front << " " << "最后一个元素为:" << Back << endl;
//使用pop_back和pop_front方法删除list中的元素,并借助元素读取方法说明读取操作成功
list1.pop_front();//删除list1中第一个元素
list1.pop_back();//删除list1中最后一个元素
int Front1 = list1.front();//再次读取第一个元素
int Back1 = list1.back();//再次读取最后一个元素
if (Front != Front1) {//原来list1对象中的元素互不相同
cout << "list对象从前面删除数据成功" << endl;
cout << "原来list1对象中第一个元素为:" << Front <<" "<< "删除后第一个元素为:" << Front1;
}
cout << " ";
if (Back != Back1) {
cout << "list对象从后面删除元素成功!" << endl;
cout << "原来list1对象中最后一个元素为:" << Back << " " << "删除后最后一个元素为:" << Back1;
}
cout << endl;
int size3 = list1.size();//读取删除数据后元素个数
cout << "删除元素后list对象中还剩下的元素为:" << size3 << "个" << endl;
//利用迭代器对list对象删除后的元素进行遍历,并且输出遍历对象
cout << "删除后的迭代序列为:";
for (list<int>::iterator iter2 = list1.begin(); iter2 != list1.end(); iter2++) {
cout << *iter2 << " ";
}
cout << endl;
//对list1对象元素进行删除
cout << "准备对list1对象进行清空操作!" << endl;
cout << "清空前list1对象还有" << list1.size() << "个" << endl;
list1.clear();
int size4 = list1.size();
if (size4 == 0) {
cout << "清空list1对象后元素还有:" << size4 << "个" << endl;
cout << "list对象元素清空成功!" << endl;
}
return 0;
}
程序运行结果见下图:
小伙伴们多加练习哦!冲冲!