STL中的List是一个双向链表。
链表是一种物理储存上不连续,逻辑上连续的数据结构。
逻辑上的连续有指针来实现。
现在不讲如何实现,来看看STL中List如何使用。
template < class T, class Alloc = allocator<T> > class list;
//list模板,第二个参数为缺省参数,是分配器,一般不需要写,第一个参数是指定List要储存的数据的类型。
构造函数:
#include <iostream>
#include <list>
int main ()
{
// constructors used in the same order as described above:
std::list<int> first; // int型 无参数的构造
std::list<int> second (4,100); // 1.为元素个数 2.所有元素的初值。
std::list<int> third (second.begin(),second.end()); // 两个参数都为同类型链表的迭代器,形成一个区间。
std::list<int> fourth (third); // 拷贝构造
//参数还可以是指针
int myints[] = {16,2,77,29};
std::list<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
//用迭代器遍历第五个链表。
std::cout << "The contents of fifth are: ";
for (std::list<int>::iterator it = fifth.begin(); it != fifth.end(); it++)
std::cout << *it << ' ';
std::cout << '\n';
return 0;
}
成员函数:begin() 与 end() 满足[ , )(前闭后开)区间
#include <iostream>
#include <list>
int main ()
{
int myints[] = {75,23,65,42,13};
std::list<int> mylist (myints,myints+5);
//begin()返回链表第一个元素的迭代器,end()返回指向最后一个元素的后一个无用的节点的迭代器
std::cout << "mylist contains:";
for (std::list<int>::iterator it=mylist.begin(); it != mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
push_back()-从后添加元素 pop_back()-从后删除元素 size()储存了第三个数据元素 empty() 判断size是否为0
#include <list>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
list<int> ilist;
cout << "size = "<<ilist.size() << endl;//初始size等于0
ilist.push_back(10);
ilist.push_back(20);
ilist.push_back(30);
cout <<"size=" <<ilist.size() << endl;//压入三个元素后 size等于3
while(ilist.empty() != true)
{
ilist.pop_back();//弹出一个元素
cout << "size = " << ilist.size() <<endl;//弹出元素后size减少
}
//元素全部删除后empty()返回true退出循环
return 0;
}
assign() 更改list内容
和构造函数的功能一样,区别是一个是初始化调用,一个是已有的对象要改变。
#include <iostream>
#include <list>
int main ()
{
std::list<int> first;
std::list<int> second;
first.assign (7,100);
second.assign (first.begin(),first.end()); // 复制first里的内容
int myints[]={1776,7,4};
first.assign (myints,myints+3); // 功能和上面的一个构造函数一样
std::cout << "Size of first: " << int (first.size()) << '\n';
std::cout << "Size of second: " << int (second.size()) << '\n';
return 0;
}
emplace()和push类似,只不过它是储存的是一对数据。
#include <iostream>
#include <list>
int main ()
{
std::list< std::pair<int,char> > mylist;//pair就是一对的意思,可以储存两种不同类型的数据。
mylist.emplace ( mylist.begin(), 100, 'x' );
mylist.emplace ( mylist.begin(), 200, 'y' );
std::cout << "mylist contains:";
for (auto& x: mylist)
std::cout << " (" << x.first << "," << x.second << ")";
std::cout << '\n';
return 0;
}