#include <list>
#include <iostream>
#include <algorithm>
using namespace std;
void print(int num)
{
cout << num << " ";
}
bool IsOdd(int i)
{
return ((i & 1) == 1);
}
int main()
{
//1. 初始化
list<int> v;
list<int>::iterator iv;
v.assign(10, 2);//將10個(gè)值為2的元素賦到list中
cout << v.size() << endl; //返回list實(shí)際含有的元素?cái)?shù)量
cout << endl;
//2. 添加
v.push_front(666);
for (int i = 0; i < 10; i++)
v.push_back(i);
for_each(v.begin(), v.end(), print);//需要#include <algorithm>
cout << endl;
cout << v.size() << endl;
cout << endl;
//3. 插入及遍歷、逆遍歷和倒轉(zhuǎn)
v.insert(v.begin(), 99);//不能+和-了
v.insert(v.end(), 99);
for_each(v.begin(), v.end(), print);
cout << endl;
for_each(v.rbegin(), v.rend(), print);//在逆序迭代器上做++運(yùn)算將指向容器中的前一個(gè)元素
cout << endl;
//一般遍歷寫法
for (iv = v.begin(); iv != v.end(); ++iv)
cout << *iv << " ";
cout << endl;
v.reverse();
for_each(v.begin(), v.end(), print);
cout << endl;
for_each(v.rbegin(), v.rend(), print);
cout << endl;
cout << endl;
//4. 排序
v.sort();//為鏈表排序,默認(rèn)是升序。
for_each(v.begin(), v.end(), print);
cout << endl;
cout << endl;
//5. 刪除
v.erase(v.begin());
for_each(v.begin(), v.end(), print);
cout << endl;
v.insert(v.begin(), 99);//還原
//刪掉鏈表中所有重復(fù)的元素
v.unique();
for_each(v.begin(), v.end(), print);
cout << endl;
//去掉所有含2的元素
v.remove(2);
for_each(v.begin(), v.end(), print);
cout << endl;
//刪掉所有奇數(shù)
v.remove_if(IsOdd);
for_each(v.begin(), v.end(), print);
cout << endl;
v.pop_front();
v.pop_back();
for_each(v.begin(), v.end(), print);
cout << endl;
cout << endl;
//6. 查詢
cout << v.front() << endl;
cout << v.back() << endl;
//7. 清空
v.clear();
cout << v.size() << endl;//0
for_each(v.begin(), v.end(), print); //已經(jīng)clear,v.begin()==v.end(),不會(huì)有任何結(jié)果。
return 0;
}
C++ STL練手(list的使用)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- vector的使用 list的使用 deque的使用 set的使用 map的使用 multiset的使用 mult...
- 頭文件 #include 構(gòu)造 成員函數(shù) li.begin()li.end()li.rbegin()li.rend...
- 野球場,是講規(guī)矩的。 野球場的人,都是有故事的。 1 在野球場子里,判斷力是真的很重要的一件事情。有時(shí)候你看著一個(gè)...
- 第十章 兩人每天一起上班一起下班,有時(shí)間就一起做飯,還有每天雷打不動(dòng)的活塞運(yùn)動(dòng),時(shí)不時(shí)的約燦烈和伯賢一起出去吃飯 ...