顺序容器

C++顺序容器

1、C++的顺序容器包括:vector、list、deque。

2、初始化顺序容器的5中方法:

  (1)Create an empty container:

    list<string> slist;

    vector<int> vec;

  (2)Create a container of some size. Each element is initialized to its default value.(Recall that the default value for the build-in arithmetic types such as int and double is 0.)

    list<int> m_list(5);

    vector<string> s_vec(5);

#include <iostream>

#include <vector>

#include <string>

using namespace std;



template<typename T>

void display(vector<T> &vec)

{

    for (int i = 0; i < vec.size(); ++i)

        cout << vec[i] << ' ';

    cout << endl;

} 



int main()

{

    vector<int> int_vec(5);

    display(int_vec);



    vector<float> float_vec(5);

    display(float_vec);



    vector<double> double_vec(5);

    display(double_vec);



    vector<char> char_vec(5);

    display(char_vec);



    vector<string> string_vec(5);

    display(string_vec);



    system("pause");

    return 0;

}

运行结果为:

  (3)Create a container of a given size and specify an inital value for each element:

  vector<int> vec(10,3);

  list<string> s_list(6,"hello");

  (4)Create a container, providing an iterator pair marking a range of elements with which to initalize the container:

  int a[]={1,2,3,4,5};

  vecotr<int> s(a,a+3);

  (5)Create a container,providing a second container object.

   list<string> a_list;

   list<sring> list_2(a_list);

3、插入、删除

  (1)push_back():在容器末尾插入元素;

  (2)pop_back():删除容器末尾的元素;

  (3)push_front():适用于list、deque容器,在容器开头插入元素;

  (4)pop_front():适用于list、deque容器,删除容器的第一个元素;

  (5)front():获取第一个元素;

  (6)back():返回最后一个元素;

 

你可能感兴趣的:(容器)