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.
This question is related to
c++
arrays
vector
declaration
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;
Source: Stackoverflow.com