标签:add new cas 根据 class algo namespace soft family for
数组具有固定的容量
,我们需要在初始化时指定数组的大小。有时它会非常不方便并可能造成浪费。
因此,大多数编程语言都提供内置的动态数组
,它仍然是一个随机存取的列表数据结构,但大小是可变的
。例如,在 C++ 中的 vector
,以及在 Java 中的 ArrayList
。
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { // 1. initialize vector<int> v0; vector<int> v1(5, 0); // 2. make a copy vector<int> v2(v1.begin(), v1.end()); vector<int> v3(v2); // 2. cast an array to a vector int a[5] = { 0, 1, 2, 3, 4 }; vector<int> v4(a, *(&a + 1)); // 3. get length cout << "The size of v4 is: " << v4.size() << endl; // 4. access element cout << "The first element in v4 is: " << v4[0] << endl; // 5. iterate the vector cout << "[Version 1] The contents of v4 are:"; for (int i = 0; i < v4.size(); ++i) { cout << " " << v4[i]; } cout << endl; cout << "[Version 2] The contents of v4 are:"; for (int& item : v4) { cout << " " << item; } cout << endl; cout << "[Version 3] The contents of v4 are:"; for (auto item = v4.begin(); item != v4.end(); ++item) { cout << " " << *item; } cout << endl; // 6. modify element v4[0] = 5; // 7. sort sort(v4.begin(), v4.end()); // 8. add new element at the end of the vector v4.push_back(-1); // 9. delete the last element v4.pop_back(); system("pause"); }
这里学习一下 auto关键字:auto可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型
ps:auto 变量必须在定义时初始化,这类似于const关键字。
标签:add new cas 根据 class algo namespace soft family for
原文地址:https://www.cnblogs.com/dmndxld/p/10783170.html