初始化 stdvector

宣告時, 可以通過多種方式初始化 std::vector

Version >= C++ 11

std::vector<int> v{ 1, 2, 3 };  // v becomes {1, 2, 3}

// Different from std::vector<int> v(3, 6)
std::vector<int> v{ 3, 6 };     // v becomes {3, 6}
// Different from std::vector<int> v{3, 6} in C++11
std::vector<int> v(3, 6);  // v becomes {6, 6, 6}

std::vector<int> v(4);     // v becomes {0, 0, 0, 0}

可以通過多種方式從另一個容器初始化向量:

複製構造(僅從另一個向量),從 v2 複製資料:

std::vector<int> v(v2);
std::vector<int> v = v2;

Version >= C++ 11

移動構造(僅從另一個向量),從 v2 移動資料:

std::vector<int> v(std::move(v2));
std::vector<int> v = std::move(v2);

迭代器(範圍)複製構造,將元素複製到 v

// from another vector
std::vector<int> v(v2.begin(), v2.begin() + 3); // v becomes {v2[0], v2[1], v2[2]}

// from an array
int z[] = { 1, 2, 3, 4 };
std::vector<int> v(z, z + 3);                   // v becomes {1, 2, 3}

// from a list
std::list<int> list1{ 1, 2, 3 };
std::vector<int> v(list1.begin(), list1.end()); // v becomes {1, 2, 3}

Version >= C++ 11

迭代器移動構造,使用 std::make_move_iterator ,將元素移動到 v

// from another vector
std::vector<int> v(std::make_move_iterator(v2.begin()),
                   std::make_move_iterator(v2.end());

// from a list
std::list<int> list1{ 1, 2, 3 };
std::vector<int> v(std::make_move_iterator(list1.begin()),
                   std::make_move_iterator(list1.end()));

assign() 成員函式的幫助下,std::vector 可以在構建後重新初始化:

v.assign(4, 100);                      // v becomes {100, 100, 100, 100}

v.assign(v2.begin(), v2.begin() + 3);  // v becomes {v2[0], v2[1], v2[2]}

int z[] = { 1, 2, 3, 4 };
v.assign(z + 1, z + 4);                // v becomes {2, 3, 4}