C++——list
1.list的介绍及使用
1.1list的介绍
a.list是可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代。
b.list的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向其前一个元素和后一个元素。
c.list与forward_list非常相似。主要的不同在于forward_list是单链表,只能朝前迭代,以让其更简单高效。
d.与其他的序列式容器相比,list通常在任意位置进行插入、移除元素的执行效率更好。
e.与其他序列容器相比,list和forward_list最大的缺陷是不支持任意位置的随机访问。
1.2list的使用
1.2.1list的构造
int main()
{
list<int> l1; //l1默认构造
list<int> l2(4, 100); //l2中为4个值为100的元素
list<int> l3(l2.begin(), l2.end()); //l3用l2的迭代器区间构造
list<int> l4(l3); //l4用l3拷贝构造
int nums[] = {
5,4,9,6,10 };
list<int> l5(nums, nums + sizeof(nums)/sizeof(int)); //以数组为迭代器区间构造
return 0;
}
1.2.2list iterator的使用
int main()
{
int nums[] = {
1,2,3,4,5,6,7,8,9 };
list<int> l(nums, nums + sizeof(nums) / sizeof(int));
//正向迭代器
list<int>::iterator it = l.begin();
while(it != l.end())
{
cout << *it << " ";
it++;
}
cout << endl;
//反向迭代器
list<int>::reverse_iterator rit = l.rbegin();
while (rit != l.rend())
{
cout << *rit << " ";
rit++;
}
cout << endl;
//const迭代器
list<int>::const_iterator cit = l.begin();
while (cit != l.end())
{
cout << *cit << " ";
cit++;
}
cout << endl;
return 0;
}
1.2.3list的增删查改
int main()
{
list<int> l;
//在list尾部插入元素
l