关于Vectors
Similar to java ArrayList.
-
C++的standard template library提供vector数据类型,而vector是一种container。
container分为两种,sequence container将数据像array一样排列好;而associate container可以让程序员直接获得elements stored in the container。container分为两种,sequence container将数据像array一样排列好;而associate container可以让程序员直接获得elements stored in the container。 -
关于定义一个 STL vector
一定要有vector的头文件,在定义的时候不需要设置大小,依然可以用array的[]来读取vector里的element。
Expression | 意义 |
---|---|
vector < int > numbers; | 此情况没有强调长度 |
vector < int > numbers (10); | 初始化长度为10 |
vector < int > numbers(10, 2); | 定义了一个长度为10,每一项初始值都为2 |
vector < int > set2 (set1); | set2是a copy of set1 |
vector < int > numbers { 10, 20, 30, 40 }; | C++ 11 Only。注意要用 { }, 而且没有等于号 |
- 一些vector的方程:
Vector方程 | 意义 |
---|---|
x = vect.at(5); | assigns the value of the 5th element of vect to x |
x = vect.capacity(); | 跟size()不一样,capacity意味着在不新allocate内存都时候,这个vect可以存多少个element |
x = vect.size(); | vect里面已经有多少个element了 |
vect.clear(); | 把vect里面都element全部清空 |
vect.empty() | 返回一个boolean值,检查这个vector是不是空的 |
vect.pop_back(); | 把vect最后的element去除,这时候vect的长度也会减一 |
vect.push_back(7); | 在vect最后加入7这个值,如果vect是空的或者满的,a new element then will be created |
vect.reverse(); | 把一个vector的顺序打乱,1234 -> 4321 |
vect.resize(n, m); | 把vect重新调整大小,变成n长度, 每一项都是initialize成m |
vect1.swap(vect2); | 把vect1 和 vect2的内容相交换 |
练习:
Write a single statement that assigns a new value to the element of the vector indexed by j. This new value should be equal to twice the value stored in the next element of the vector (i.e. the element after the element indexed by j).Do not modify any other elements of the vector! (From: codelab)
答案: a.at(j) = 2 * a.at(j+1);
Reference: Gaddis, Tony. Starting out with C++ . Pearson, 2019.