我想初始化一个向量就像我们在数组中做的那样。
例子
int vv[2] = {12, 43};
但是当我这样做的时候,
vector<int> v(2) = {34, 23};
OR
vector<int> v(2);
v = {0, 9};
它给出一个错误:
'{'令牌前期望的主表达式
AND
错误:expect ', ' or '; ' before ' = '令牌
分别。
我想初始化一个向量就像我们在数组中做的那样。
例子
int vv[2] = {12, 43};
但是当我这样做的时候,
vector<int> v(2) = {34, 23};
OR
vector<int> v(2);
v = {0, 9};
它给出一个错误:
'{'令牌前期望的主表达式
AND
错误:expect ', ' or '; ' before ' = '令牌
分别。
使用新的c++标准(可能需要在编译器上启用特殊标志),您可以简单地做到:
std::vector<int> v { 34,23 };
// or
// std::vector<int> v = { 34,23 };
甚至:
std::vector<int> v(2);
v = { 34,23 };
在不支持此功能(初始化列表)的编译器上,您可以使用数组来模拟此功能:
int vv[2] = { 12,43 };
std::vector<int> v(&vv[0], &vv[0]+2);
或者,对于赋值到现有向量的情况:
int vv[2] = { 12,43 };
v.assign(&vv[0], &vv[0]+2);
就像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; }
然后你可以这样做,而不需要重复整个大小:
int vv[] = { 12,43 };
std::vector<int> v(begin(vv), end(vv));
你也可以这样做:
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_;
};
像这样使用它:
std::vector<int> v = make_vector<int>() << 1 << 2 << 3;