Library type vector
represents a collection of objects, where all objects are the same type.
Because vector
the houses other objects, it is often referred to as a container.
To use the vector
need to include the header file <vector>
.
vector
It is not a template type, a vector
type produced must contain vector
the type of elements, for example: vector<int>
.
Definition and initialization vector objects
- List initialize
vector
objects
vector<string> articles = {"a","an","the"};
- Create a specified number of elements
vector<int> ivec(10,-1);
- Initialization value
vector<int> ivec(10); //10个元素,每个都初始化为0
vector<string> svec(10); //10个元素,每个都是空string对象
- A list of the initial value or the number of elements
vector<int> v1(10); //v1有10个元素,每个值都是0
vector<int> v2{ 10 }; //v2有1个元素,其值为10
vector<int> v3(10, 1); //v3有10个元素,每个值都是1
vector<int> v4{ 10, 1 }; //v4有2个元素,值分别是10和1
vector<string> v5{ "hi" }; //列表初始化,v5有一个元素
vector<string> v6("hi"); //错误,不能使用字符串字面值构建vector对象
vector<string> v7(10); //v7有10个默认初始化的元素
vector<string> v8{ 10, "hi"}; //v8有10个值为"hi"的元素
vector Compatible Operating
Not in the form of the additive elements with subscript
vector<int> ivec;
for(decltype(ivec.size())ix = 0;ix!=10;++ix)
ivec[ix] = ix; //严重错误,ivec不包含任何元素
vector
Objects and string
object subscript operator may be used to access an element already present, but not in an additive element. '