[c++] How to initialize a vector in C++

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

The answer is


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;

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to vector

How to plot vectors in python using matplotlib How can I get the size of an std::vector as an int? Convert Mat to Array/Vector in OpenCV Are vectors passed to functions by value or by reference in C++ Why is it OK to return a 'vector' from a function? Append value to empty vector in R? How to initialize a vector with fixed length in R How to initialize a vector of vectors on a struct? numpy matrix vector multiplication Using atan2 to find angle between two vectors

Examples related to declaration

Component is part of the declaration of 2 modules What is the 'open' keyword in Swift? What’s the difference between “{}” and “[]” while declaring a JavaScript array? Getting error: ISO C++ forbids declaration of with no type What is an 'undeclared identifier' error and how do I fix it? Difference between int32, int, int32_t, int8 and int8_t forward declaration of a struct in C? How to initialize a vector in C++ Declare variable in SQLite and use it Initializing multiple variables to the same value in Java