vector 称为容器,是一个类模板。
(一)初始化和定义
vector<T> v1; vector保存类型为T的对象,默认构造函数v1为空。
vector<T> v2(v1); v2是v1的一个副本。
vector<T> v3(n,i); v3包含n个值为i的元素。
vector<T> v4(n); v4含有值初始化的元素的n个副本。
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
vector<string> v1(10, "hello");
cout << v1[5] << endl;
return 0;
}
vector的动态增长:vector对象(以及其他标准库对象)的重要属性就在于可以在运行时高效的添加元素。
值初始化:如果没有指定元素的初始化式,那么标准库将自行提供一个元素初始值初始化。包括:
- T为内置类型
- 有构造函数的类类型
- 没有定义任何构造函数的类类型
(二)vector对象的操作
v1.empty();
v1.size(); //只能获取已经存在的元素,不会添加新元素
v1.push_back(); //在最后位置,追加元素
v1.pop_back();
v1[];
v1 = v2;
>,>=,<,<=,!= //关系操作符
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
vector<string> v1(5, "hello");
cout << "v1[4]: " << v1[4] << endl;
v1.push_back("thanks");
for(int ix = 0; ix != v1.size(); ++ix)
cout << v1[ix] << endl;
v1.pop_back();
for(ix = 0; ix != v1.size(); ++ix)
cout << v1[ix] << endl;
cout << v1.size() << endl;
return 0;
}