C++ STL list(强大到想扔了C)
(一)了解listlist是一个十分强大的链表容器概念!可以进行各种遍历、插入、删除、去重、合并、拼接、排序等。(二)Test_Demo#include <iostream>#include <list>//链表结构using namespace std;int main(){/***************Demo1 list define...
·
(一)了解list
list是一个十分强大的链表容器概念!
可以进行各种遍历、插入、删除、去重、合并、拼接、排序等。
(二)Test_Demo
#include <iostream>
#include <list>//链表结构
using namespace std;
int main()
{
/***************Demo1 list definee*************************/
list<int> lint0;
list<int> lint1{ 1, 2, 3 };
list<int> lint2(lint1);
list<int> lint3 = lint1;
list<int> lint4 = {1, 0, 9, 8};
/***************Demo list options*****************************/
//正反向迭代遍历list
for (auto it : lint1) {
cout << it << " ";
}
cout << endl;
//正向迭代
for (list<int>::iterator it = lint1.begin(); it != lint1.end(); ++it) {
cout << *it << " ";
}
cout << endl;
//反向迭代
for (auto it = lint1.rbegin(); it != lint1.rend(); ++it) {
cout << *it << " ";
}
cout << endl;
//const正向迭代
for (auto it = lint1.cbegin(); it != lint1.cend(); ++it) {
cout << *it << " ";
}
cout << endl;
//在list的头尾插入 一个 数据
lint1.push_back(9);
lint1.push_front(10);
for (auto it : lint1) {
cout << it << " ";
}
lint1.insert(lint1.begin()++, 11); //在list任意位置(迭代器位置参数)插入one数据
cout << endl;
//删除数据 与 清空list
lint1.pop_back();
lint1.pop_front();
for (auto it : lint1) {
cout << it << " ";
}
cout << endl;
lint1.erase(lint1.begin()++);//在list任意位置(迭代器位置参数)删除one数据
lint1.remove(3); //删除一个value = 3
//remove_if(comp) 删除条件满足的元素,参数为自定义的回调函数
lint1.clear();
if (lint1.empty())
cout << "lint1 is empty!" << endl;
else
cout << "lint1.clear() failed!" << endl;
//size
for (auto it : lint2) {
cout << it << " ";
}
cout << endl;
cout << "size = " << lint2.size() << "\tmax_size = " << lint2.max_size() << endl;
//排序
lint4.sort();//默认升序
for (auto it : lint4) {
cout << it << " ";
}
cout << endl;
//lint4.sort(sortfunc) 自定义条件排序
//mager two list
lint2.merge(lint4); //有序(升序)合并,会释放掉lint4
for (auto it : lint2) {
cout << it << " ";
}
cout << endl;
if (lint4.empty())
cout << "lint4 have been free!" << endl;
//or lint2.merage(lint4, comp);自定义条件合并
//连接two list
lint2.splice(lint2.begin(), lint3);//将整个lint3拼接在lint2.begin(), 并free lint3
//lint2.splice(lint2.begin(), lint3, lint3.begin());//将lint3.begin() 这个元素 拼接在lint2.begin(), 并free lint3.begin()
//将[lint3.begin(), lint3.end()++] 这段元素 拼接在lint2.begin(), 并free 这个区间的元素
//lint2.splice(lint2.begin(), lint3, lint3.begin(), lint3.end()++);
for (auto it : lint2) {
cout << it << " ";
}
cout << endl;
//反转list
lint2.reverse();
for (auto it : lint2) {
cout << it << " ";
}
cout << endl;
//去重
lint2.unique();
for (auto it : lint2) {
cout << it << " ";
}
cout << endl;
return 0;
}
更多推荐
已为社区贡献1条内容
所有评论(0)