c++序列容器

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

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

向量vector:

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

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

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

 vector的声明有:

vector<int>a;		//declare an empty int vector
vector<int>a(5);	//declare a vector with five element
vector<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 intvector
	a.push_back(4);		//input data
	a.push_back(6);
	a.push_back(3);
        a.insert(a.begin()+2,5);	//insert data into the vector third
	a.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 element
	for(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 deque
deque<int>a(5);		//declare a deque with five element
deque<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 deque
	a.insert (a.begin ()+2,6);	//insert element into the deque third
	a.push_back (4);		//put the element at the ending of the deque
	for(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 list
list<int>a(5);		//declare a list with five element
list<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 point
	a.push_back (4);
	a.push_back (7);
	a.push_back (2);
	a.push_front (8);		//put the element in the list beginning
	a.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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值