(二)STL:序列式容器——list的常见用法 (一)STL:序列式容器——vector的常见用法

 list是由双向链表实现的,每个节点存储一个元素,list支持前后两种移动方向,其特点如下:

    (1).list不支持随机存取

    (2).在list的任何位置执行元素的插入和移除都非常快,插入和删除动作不会影响指向其他

         元素的指针,引用,迭代器

     (3).list不支持随机存取,不提供下标操作符和at()函数

1.list的定义和赋值

    list模板类提供了两个成员函数push_front()和push_back(),用来把新元素插入list对象中,

    push_front()用来在容器的头部插入新元素,push_back()用来在容器的尾部插入元素

    (1).push_front()函数      

list<int> ListInt;
	
list<int>::iterator iter;

//头部插入元素
ListInt.push_front(1);
ListInt.push_front(2);
ListInt.push_front(3);
ListInt.push_front(4);
ListInt.push_front(5);
ListInt.push_front(3);

for (iter = ListInt.begin(); iter != ListInt.end(); iter++)
{
    cout << *iter << ",";
}
cout << endl;

    输出结果:

        

    (2).push_back()    

#include <iostream>
#include <list>
#include <algorithm>

using namespace std;

int main()
{
    list<int> ListInt;
	
    list<int>::iterator iter;

    //尾部插入元素
    ListInt.push_back(1);
    ListInt.push_back(2);
    ListInt.push_back(3);
    ListInt.push_back(4);
    ListInt.push_back(5);
    ListInt.push_back(3);

    for (iter = ListInt.begin(); iter != ListInt.end(); iter++)
    {
	cout << *iter << ",";
    }
    cout << endl;
    return 0;
}

输出结果如下:

    

(3).元素重置

       在list型容器中提供了可以重置元素值的成员函数assign(),使用函数assign()可以修改容器任意

       元素的值,甚至可以修改多个连续元素的数字,assign()函数的原型如下:

        void assign(const_iterator first, const_iterator last);

        void assign(size_type n, const T& x=T());

#include <iostream>
#include <list>
#include <algorithm>

using namespace std;

void Print(int &ListInt)
{
    cout << ListInt << ",";
}

int main()
{
    list<int> ListOne, ListTwo, ListThree;

    for (int i = 0; i < 5; i++)
    {
         ListOne.push_back(i);
    }

    ListTwo.assign(ListOne.begin(), ListOne.end());

    ListThree.assign(4, 5);

    for_each(ListOne.begin(), ListOne.end(), Print);
    cout << endl;

    for_each(ListTwo.begin(), ListTwo.end(), Print);
    cout << endl;

    for_each(ListThree.begin(), ListThree.end(), Print);
    cout << endl;

    return 0;
}

输出结果如下:

    

(4).元素的删除

  list型容器可以在序列的开头和队删除元素,其成员函数包括:pop_back(),pop_front(),erase和clear

  pop_front()和pop_back()函数的使用

while (!ListInt.empty())
{
    //返回首部元素
    cout << ListInt.front() << ",";
    //删除首部元素
    ListInt.pop_front();
}
while (!ListInt.empty())
{
    //返回队尾元素
    cout << ListInt.back() << ",";
    //删除队尾元素
    ListInt.pop_back();
}
erase()函数的使用(与vector的用法一致)

(一)STL:序列式容器——vector的常见用法


       

    

猜你喜欢

转载自blog.csdn.net/zkk_18815518722/article/details/80777246