#include <iostream>
#include <list>
#include <vector>
using namespace std;
void demo1(void) {
list<int> listInt;
vector<int> vectInt;
int x = vectInt.capacity();//vector的内存空间是预先分配的
cout << "listInt size:" << listInt.size() << endl;
/*vectInt.push_back(1);
cout << "vector size:" << x << " " << vectInt.size() << endl;*/
listInt.push_back(1);
listInt.push_back(2);
listInt.push_back(3);
listInt.push_back(4);
listInt.push_back(5);
listInt.pop_front();// 2 3 4 5
listInt.pop_back();//2 3 4
listInt.push_front(7);//7 2 3 4
cout << "listInt 中的成员:" << endl;
for (list<int>::iterator it = listInt.begin(); it != listInt.end(); it++) {
cout << *it << " ";
}
cout << endl;
int iFront = listInt.front();
int iBack = listInt.back();
cout << iFront << " " << iBack << endl;
listInt.front() = 520;
listInt.back() = 1314;
cout << "list 中的成员:" << endl;
for (list<int>::iterator it = listInt.begin(); it != listInt.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
//list的用法
void demo2(void) {
list<int> listIntA,listIntB;
listIntA.push_back(1);
listIntA.push_back(3);
listIntA.push_back(5);
listIntA.push_back(7);
listIntA.push_back(9);
listIntB.assign(++listIntA.begin(), --listIntA.end());
cout << "listIntB 中的成员:" << endl;
for (list<int>::iterator it = listIntB.begin(); it != listIntB.end(); it++) {
cout << *it << " ";
}
cout << endl;
//list的删除
//1.erase的用法
list<int>::iterator itBegin = listIntA.begin();
++itBegin;
list<int>::iterator itEnd = listIntA.begin();
++itEnd;
++itEnd;
++itEnd;
listIntA.erase(listIntA.begin());
listIntA.erase(itBegin, itEnd);
cout << "listIntA 中的成员:" << endl;
for (list<int>::iterator it = listIntA.begin(); it != listIntA.end(); it++) {
cout << *it << " ";
}
cout << endl;
//remove的用法
//1.直接调用remove方法
listIntA.push_back(9);
listIntA.push_back(4);
listIntA.remove(9);
cout << "listIntA 中的成员:" << endl;
for (list<int>::iterator it = listIntA.begin(); it != listIntA.end(); it++) {
cout << *it << " ";
}
cout << endl;
//2.遍历然后逐个删除
for (list<int>::iterator it = listIntA.begin(); it != listIntA.end(); ) {
if (*it == 4) {
it = listIntA.erase(it);
}
else {
it++;
}
}
cout << "listIntA 中的成员:" << endl;
for (list<int>::iterator it = listIntA.begin(); it != listIntA.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
//list 的反序排列
void demo3(void) {
list<int> listInt;
listInt.push_back(1);
listInt.push_back(2);
listInt.push_back(3);
listInt.push_back(4);
listInt.push_back(5);
listInt.reverse();
cout << "list 中的成员:" << endl;
for (list<int>::iterator it = listInt.begin(); it != listInt.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
// list不可以随机存取元素,所以不支持at.(position)函数与[]操作符。
// 可以对其迭代器执行++,但是不能这样操作迭代器:it+3
int main(void) {
demo3();
system("pause");
return 0;
}
list容器
最新推荐文章于 2024-07-15 14:42:50 发布