Sequence container in STL-list (list)

Sequence container in STL-list (list)

List is a list type, it can hold many types of data, such as several integers, so it is called a container.
list is an important member of the C++ STL, you need to include the header file when using it:

#include <list>;

The advantage of the list is that it is very fast to perform insert and delete actions at any position, because only the link is changed.

1. Initialization of list

There are the following ways, examples are as follows:

list<int> listname;
list<int> listname(5);
list<int> listname(5,1);//包含5个元素1的列表
list<int> listname(elselist);
list<int> listname(elselist.begin(),elselist.end());
int b[7]={
    
    1,2,3,4,5,9,8};list<int> a(b,b+7); //从数组中获得初值

Two, the important operations of the list object

Listed as follows:

a.assign(b.begin(), b.begin()+3); //b为列表,将b的0~2个元素构成的列表赋给a
a.assign(4,2); //是a只含4个元素,且每个元素为2
a.back(); //返回a的最后一个元素
a.front(); //返回a的第一个元素
a.clear(); //清空a中的元素
a.empty(); //判断a是否为空,空则返回ture,不空则返回false
a.erase(a.begin()+1,a.begin()+3); //删除a中第1个(从第0个算起)到第2个元素,也就是说删除的元素从a.begin()+1算起(包括它)一直到a.begin()+ 3(不包括它)
a.push_back(5);//在a的最后一个列表后插入一个元素,其值为5
a.push_front(5);//在a的最前一个列表前插入一个元素,其值为5
a.pop_front();//从容器的首部移走数据
a.pop_back();//从容器的尾部移走数据
a.insert(a.begin()+1,5); //在a的第1个元素(从第0个算起)的位置插入数值5,如a为1,2,3,4,插入元素后为1,5,2,3,4
a.insert(a.begin()+1,3,5); //在a的第1个元素(从第0个算起)的位置插入3个数,其值都为5
a.insert(a.begin()+1,b+3,b+6); //b为数组,在a的第1个元素(从第0个算起)的位置插入b的第3个元素到第5个元素(不包括b+6),如b为1,2,3,4,5,9,8 ,插入元素后为1,4,5,9,2,3,4,5,9,8
a.remove(5); //从list中删除元素5
a.merge(b); //调用结束后b变为空,a中元素包含原来a和b的元素
a.size(); //返回a中元素的个数
a.max_size(); //返回最大容量
a.reverse(); //可以实现a的逆置
a.resize(10); //将a的现有元素个数调至10个,多则删,少则补,其值随机
a.resize(10,2); //将a的现有元素个数调至10个,多则删,少则补,其值为2
a.swap(b); //将a中的元素和b中的元素进行整体性交换
a.sort(); //默认从小到大进行排序
a.sort(greater<int>()); //从大到小排序
a.unique(); //移除list中相邻的重复元素,只保留一个
a.splice(); //将其他list合并到a
//如,将elselist整个列表合并到mylist的后面,此时elselist变为空
//mylist.splice(mylist.end(),elselist)
//如,将将elselist的第一个元素合并到mylist后面,此时elselist减少一个元素
//mylist.splice(mylist.end(),elselist,elselist.begin())
//如,将elselist的迭代器区间的元素合并到mylist,此时elselist减少响应的区间元素:
//mylist.splice(mylist.end(),elselist,elselist.begin(),elselist.end())
a==b; //列表的比较操作还有!=,>=,<=,>,<

Three, the way to access vector sequentially

Examples are as follows:

//列表a中添加元素
list<int> a;
for(int i=0;i<10;i++)
a.push_back(i);

//也可以从数组中选择元素向列表中添加
int a[6]={
    
    1,2,3,4,5,6};
list<int> b;
for(int i=1;i<=4;i++)
b.push_back(a[i]);

//也可以从现有向量中选择元素向列表中添加
int a[6]={
    
    1,2,3,4,5,6};
list<int> b;
list<int> c(a,a+4);
for(list<int>::iterator it=c.begin();it<c.end();it++)
b.push_back(*it);

//也可以从文件中读取元素向列表中添加
ifstream in("data.txt");
list<int> a;
for(int i; in>>i)
a.push_back(i);

Guess you like

Origin blog.csdn.net/hyl1181/article/details/108559027
Recommended