c++序列容器

来源:互联网 发布:自动充值软件 编辑:程序博客网 时间:2024/04/28 04:47

容器是存储多个数据的一种形式,容器有很多种。

序列容器有三种,分别是向量(vector)、双端队列(deque)和链表(list)。

向量vector:

vector相当于可变长度数组,它可以用数组的方式去输入和输出,并且它的大小可变的;

vector访问元素是可以使 用下标来访问。

使用vector时要有#include<vector>头文件。

 vector的声明有:

vector<int>a;//declare an empty int vectorvector<int>a(5);//declare a vector with five elementvector<int>a(5,1);//declare an initial value of 5 element and 1 of the initial value of the vector

vector的应用:

#include<vector>void main(){int i;vector<int>a;//define a intvectora.push_back(4);//input dataa.push_back(6);a.push_back(3);        a.insert(a.begin()+2,5);//insert data into the vector thirda.push_back(9);a.push_back(2);for(i=0;i<a.size();i++){cout<<a[i]<<endl;}cout<<endl;a.pop_back();//delete the last elementfor(int j=0;j<a.size();j++){cout<<a[j]<<endl;}}

vector输入的数据一般都是在向量的后面,只有用插入(insert)时可以随机插入。


双端队列deque:
deque和vector向量相似,可以用数组的方式输入、输出,它的大小也是可变的,但是deque能直接把数据插入到队列前面,而vector不能。
使用deque时要包括#include<deque>头文件;
deque的声明:

deque<int>a;//declare an empty int dequedeque<int>a(5);//declare a deque with five elementdeque<int>a(5,1);//declare an initial deque of 5 element and 1 of the initial value of the deque

deque的应用:

#include<deque>void main(){deque<int>a(4);a.push_front (7);//put the element at the beginning of the dequea.insert (a.begin ()+2,6);//insert element into the deque thirda.push_back (4);//put the element at the ending of the dequefor(int i=0;i<a.size();i++){cout<<a[i]<<endl;}system("pause");}

链表list:

list容器是链表,它和vetor不同,不能用数组表示,输出时只能用容器元素的指针(iterator)来进行输出。

访问list元素要用指针从begin或end开始,

list的声明:

list<int>a;//declare an empty int listlist<int>a(5);//declare a list with five elementlist<int>a(5,1);//declare an initial list of 5 element and 1 of the initial value of the list
list的应用:

</pre><pre name="code" class="cpp">#include<list>void main(){list<int>a;list<int>::iterator t;//define a iteraotr pointa.push_back (4);a.push_back (7);a.push_back (2);a.push_front (8);//put the element in the list beginninga.push_back (6);a.push_back (3);t=a.begin();while(t!=a.end()){cout<<*t++<<endl;}cout<<endl;t=a.end ();list<int>::iterator p=t;while(p!=a.begin()){cout<<*--p<<endl;}system("pause");}






0 0
原创粉丝点击