如何在 C++ 中初始化向量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8906545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to initialize a vector in C++
提问by Md Faisal
I want to initialize a vector like we do in case of an array.
我想初始化一个向量,就像我们在数组的情况下所做的那样。
Example
例子
int vv[2] = {12, 43};
But when I do it like this,
但是当我这样做时,
vector<int> v(2) = {34, 23};
OR
或者
vector<int> v(2);
v = {0, 9};
it gives an error:
它给出了一个错误:
expected primary-expression before ‘{' token
'{' 标记前的预期主表达式
AND
和
error: expected ‘,' or ‘;' before ‘=' token
错误:预期的 ',' 或 ';' 在 '=' 标记之前
respectively.
分别。
回答by R. Martinho Fernandes
With the new C++ standard (may need special flags to be enabled on your compiler) you can simply do:
使用新的 C++ 标准(可能需要在编译器上启用特殊标志),您可以简单地执行以下操作:
std::vector<int> v { 34,23 };
// or
// std::vector<int> v = { 34,23 };
Or even:
甚至:
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);
Like James Kanze suggested, it's more robust to have functions that give you the beginning and end of an array:
就像 James Kanze 建议的那样,拥有为您提供数组开头和结尾的函数会更健壮:
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));
回答by Viktor Sehr
You can also do like this:
你也可以这样做:
template <typename T>
class make_vector {
public:
typedef make_vector<T> my_type;
my_type& operator<< (const T& val) {
data_.push_back(val);
return *this;
}
operator std::vector<T>() const {
return data_;
}
private:
std::vector<T> data_;
};
And use it like this:
并像这样使用它:
std::vector<int> v = make_vector<int>() << 1 << 2 << 3;