[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};

But when I do it like this,

vector<int> v(2) = {34, 23};


vector<int> v(2);
v = {0, 9};

it gives an error:

expected primary-expression before ‘{’ token


error: expected ‘,’ or ‘;’ before ‘=’ token


This question is related to c++ arrays vector declaration

The answer is

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 };

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:

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));

You can also do like this:

template <typename T>
class make_vector {
  typedef make_vector<T> my_type;
  my_type& operator<< (const T& val) {
    return *this;
  operator std::vector<T>() const {
    return data_;
  std::vector<T> data_;

And use it like this:

std::vector<int> v = make_vector<int>() << 1 << 2 << 3;

Questions with c++ tag:

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++ How to enable C++17 compiling in Visual Studio? Remove from the beginning of std::vector Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? What is (x & 1) and (x >>= 1)? What are the new features in C++17? Visual Studio Code includePath Compiling an application for use in highly radioactive environments "No rule to make target 'install'"... But Makefile exists How to build and use Google TensorFlow C++ api Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) Converting std::__cxx11::string to std::string lvalue required as left operand of assignment error when using C++ How to overcome "'aclocal-1.15' is missing on your system" warning? MSVCP140.dll missing How to get image width and height in OpenCV? CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found Reading json files in C++ What exactly is std::atomic? Compile c++14-code with g++ Visual Studio 2015 doesn't have cl.exe Visual Studio 2013 error MS8020 Build tools v140 cannot be found CMake does not find Visual C++ compiler Casting int to bool in C/C++ C++ How do I convert a std::chrono::time_point to long and back How can I get the size of an std::vector as an int? Significance of ios_base::sync_with_stdio(false); cin.tie(NULL); Fatal error: iostream: No such file or directory in compiling C program using GCC unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2 How to end C++ code How to change text color and console color in code::blocks? Error: stray '\240' in program invalid use of non-static member function Convert float to string with precision & number of decimal digits specified? enum to string in modern C++11 / C++14 / C++17 and future C++20 Passing capturing lambda as function pointer How do I add a library path in cmake? error: expected primary-expression before ')' token (C) undefined reference to 'std::cout' java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader fatal error: mpi.h: No such file or directory #include <mpi.h>

Questions with arrays tag:

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? How to update an "array of objects" with Firestore? How to increment a letter N times per iteration and store in an array? Cloning an array in Javascript/Typescript use Lodash to sort array of object by value TypeScript enum to object array How do I check whether an array contains a string in TypeScript? How to use forEach in vueJs? Program to find largest and second largest number in array How to plot an array in python? How to add and remove item from array in components in Vue 2 console.log(result) returns [object Object]. How do I get result.name? How to map an array of objects in React How to define Typescript Map of key value pair. where key is a number and value is an array of objects Removing object from array in Swift 3 How to group an array of objects by key Find object by its property in array of objects with AngularJS way Getting an object array from an Angular service push object into array How to get first and last element in an array in java? Add key value pair to all objects in array How to convert array into comma separated string in javascript Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0) Angular 2 declaring an array of objects How can I loop through enum values for display in radio buttons? How to convert JSON object to an Typescript array? Angular get object from array by Id Add property to an array of objects Declare an array in TypeScript ValueError: all the input arrays must have same number of dimensions How to convert an Object {} to an Array [] of key-value pairs in JavaScript Check if a value is in an array or not with Excel VBA TypeScript add Object to array with push Filter array to have unique values remove first element from array and return the array minus the first element merge two object arrays with Angular 2 and TypeScript? Creating an Array from a Range in VBA "error: assignment to expression with array type error" when I assign a struct field (C) How do I filter an array with TypeScript in Angular 2? How to generate range of numbers from 0 to n in ES2015 only? TypeError: Invalid dimensions for image data when plotting array with imshow()

Questions with vector tag:

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 Debug assertion failed. C++ vector subscript out of range Displaying a vector of strings in C++ Initializing a two dimensional std::vector Python: Differentiating between row and column vectors Octave/Matlab: Adding new elements to a vector splitting a string into an array in C++ without using vector How do you create vectors with specific intervals in R? How to read a file into vector in C++? Arrays vs Vectors: Introductory Similarities and Differences C++ for each, pulling from vector elements How to turn a vector into a matrix in R? Rotating a Vector in 3D Space How do I pass multiple ints into a vector at once? Convert a row of a data frame to vector Convert R vector to string vector of 1 element Get array elements from index to end Initialize empty vector in structure - c++ How to create a numeric vector of zero length in R Vector of Vectors to create matrix C++ compile time error: expected identifier before numeric constant How do I print out the contents of a vector? How to create a vector of user defined size but with no predefined values? How to fix this Error: #include <gl/glut.h> "Cannot open source file gl/glut.h" C++ delete vector, objects, free memory Using std::max_element on a vector<double> How can I get the max (or min) value in a vector? How to implement 2D vector array? Sorting a vector in descending order How to initialize a vector in C++ How do I reverse a C++ vector? What is the simplest way to convert array to vector? Converting a vector<int> to string How to cin to a vector How to copy std::string into std::vector<char>? Vector of structs initialization Adding to a vector of pair List distinct values in a vector in R Choice between vector::resize() and vector::reserve() "Cannot allocate an object of abstract type" error Convert data.frame column to a vector?

Questions with declaration tag:

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 Define a global variable in a JavaScript function Meaning of = delete after function declaration More elegant way of declaring multiple variables at the same time What are forward declarations in C++? How to declare variable and use it in the same Oracle SQL script? Assign multiple values to array in C Defining static const integer members in class definition How to create an Array, ArrayList, Stack and Queue in Java? Is it possible to declare two variables of different types in a for loop? What happens to a declared, uninitialized variable in C? Does it have a value? What is the difference between a definition and a declaration? Cannot refer to a non-final variable inside an inner class defined in a different method What’s the difference between "Array()" and "[]" while declaring a JavaScript array? Meaning of 'const' last in a function declaration of a class? Declaring multiple variables in JavaScript Why is volatile needed in C?