C++中vector概念

C++提供了使用抽象进行高效率编程的方式。标准库就是一个很好的例子:

标准库定义了许多容器类以及一系列泛型算法,是程序员可以更加简洁、抽象和有效地编写程序。

容器容纳特定类型对象的集合,

顺序容器:

它是将单一类型元素聚集起来成为容器,然后根据位置来存储和访问这些元素,这就是顺序容器,顺序容器的元素排列次序与元素值无关,而是由元素添加到容器里的次序决定。

标准库中定义了三种顺序容器类型:

vector;

list;

deque

标准库还提供了三种容器适配器(adaptor)如下:

stack;

queue;

priority_queue.


vector例子一:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
	vector<int> vec;
	vector<int> vec1(10, -1);
	vector<int> vecMyHouse(10); //define a known length vector.
	vec = vec1;
	int i;
	cout << "Please input a integer:";
	cin >> i;
	vecMyHouse.resize(i);
	for(i = 0; i < vecMyHouse.size(); i++)
	{
		vecMyHouse[i] = i;
	}
	for(i = 0; i < vecMyHouse.size(); i++)
	{
		cout << vecMyHouse[i] << endl;
	}
//	vec.clear();
	vec.push_back(100);
	for(i = 0; i < vec.size(); i++)
	{
		cout << vec[i] << endl;
	}

	cout << vecMyHouse.size() << endl;
	system("pause");
	return 0;
}

vector示例二:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
	int num;
	string word;
	vector<string> text;
	cout << "Please input the number of element that we want to insert:";
	cin >> num;
	cout << "Please input the element that we should insert:" << endl;
	while((cin >> word) && (--num))
	{
		text.push_back(word);
	}
	cout <<"First Method:\n";
	cout << "Words read are:\n";
	for(int i = 0; i < text.size(); i++)
	{
		cout << text[i] << endl;
	}

	cout << "Second Method" << endl;
	cout << "Words read are:\n";
	for(vector<string>::iterator it = text.begin(); it != text.end(); ++it)
	{
		cout << *it << endl;
	}

	system("pause");
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值