如何在 C++ 中初始化向量 [英] How to initialize a vector in C++
问题描述
我想初始化一个向量,就像我们在数组的情况下所做的那样.
I want to initialize a vector like we do in case of an array.
示例
int vv[2] = {12, 43};
但是当我这样做时,
vector<int> v(2) = {34, 23};
或
vector<int> v(2);
v = {0, 9};
它给出了一个错误:
'{' 标记前的预期主表达式
expected primary-expression before ‘{’ token
和
错误:在="标记之前应为,"或;"
error: expected ‘,’ or ‘;’ before ‘=’ token
分别.
推荐答案
使用新的 C++ 标准(可能需要在编译器上启用特殊标志),您可以简单地执行以下操作:
With the new C++ standard (may need special flags to be enabled on your compiler) you can simply do:
std::vector<int> v { 34,23 };
// or
// std::vector<int> v = { 34,23 };
甚至:
std::vector<int> v(2);
v = { 34,23 };
在不支持这个特性(初始化列表)的编译器上,你可以用一个数组来模拟它:
On compilers that don't support this feature (initializer lists) yet you can emulate this with an array:
int vv[2] = { 12,43 };
std::vector<int> v(&vv[0], &vv[0]+2);
或者,对于分配给现有向量的情况:
Or, for the case of assignment to an existing vector:
int vv[2] = { 12,43 };
v.assign(&vv[0], &vv[0]+2);
就像 James Kanze 建议的那样,拥有提供数组开头和结尾的函数会更健壮:
Like James Kanze suggested, it's more robust to have functions that give you the beginning and end of an array:
template <typename T, size_t N>
T* begin(T(&arr)[N]) { return &arr[0]; }
template <typename T, size_t N>
T* end(T(&arr)[N]) { return &arr[0]+N; }
然后你就可以做到这一点,而不必全部重复大小:
And then you can do this without having to repeat the size all over:
int vv[] = { 12,43 };
std::vector<int> v(begin(vv), end(vv));
这篇关于如何在 C++ 中初始化向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!