How to Initialize a Vector in C++

What is the easiest way to initialize a std::vector with hardcoded elements?

One method would be to use the array to initialize the vector

static const int arr[] = {16,2,77,29};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );

Vector initialization in C++17

Prior to C++17 you MUST specify vector's type through template:

std::vector<int> v{1, 2, 3};

C++17 instead allows for "deduction", which is why your code compiles even without specifying the type contained in your vector. You can read more about it here.

Generally I'd suggest to specify the type for readability even if deduction would do what you want it to.

Initializing a vector of c-strings

Well, I realize this is a silly question, once I know the answer.
From cppreference.com:

String literals have static storage duration, and thus exist in memory for the life of the program.

That explains everything.

Is it possible to initialize new std::vector in one line?

I just wonder if is possible to new and initialize a std::vector at
the same time, something like, do the two things in one line?

Yes, you can, via std::initializer_list constructor10 of std::vector

constexpr vector( std::initializer_list<T> init,
const Allocator& alloc = Allocator() ); (since C++20)

With you can write

std::vector<int>* vec = new std::vector<int>{3, 4};


Because I need a vector that create on heap!

The terms we use in C++ are automatic and dynamic storage. In most of the cases, you do not require the std::vector<int> to be allocated dynamically, rather the elements to be there. For this, you need simply a vector of integers.

std::vector<int> vec {3, 4};

However, if you're meant for a multidimensional vector, then I will suggest having a vector of vector of inters:

std::vector<std::vector<int>> vec{ {3, 4} };

When the inner vector has the same number of length, keep a single std::vector and manipulate the indexes for acting as a two-dimensional array.

In both cases, the std::vector in the background does the memory management for you.

c++ std vector initialize with existing objects

Is there a vector constructor or another technique to initialize the vector with only 1 copy?

If you move the local objects into an array, you can construct the vector from that array, eg:

// local objects 
Location locs[3]{ {1, 2}, {3, 4}, {5, 6} };

// code that updates locs ...

// construct vector
std::vector<Location> pointsVec {locs, locs+3};

Online Demo

Another option would be to simply get rid of the local objects altogether, construct them inside the vector to begin with, and then just refer to those elements, eg:

// construct vector 
std::vector<Location> pointsVec{ {1, 2}, {3, 4}, {5, 6} };

// local objects
Location &l1 = pointsVec[0];
Location &l2 = pointsVec[1];
Location &l3 = pointsVec[2];

// code that updates l1, l2, l3 ...

How to initialize a vector in C++

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

how can we initialize a vector with all values 0 in C++

You can use:

std::vector<int> v(100); // 100 is the number of elements.
// The elements are initialized with zero values.

You can be explicit about the zero values by using:

std::vector<int> v(100, 0);

You can use the second form to initialize all the elements to something other than zero.

std::vector<int> v(100, 5); // Creates object with 100 elements.
// Each of the elements is initialized to 5

How to initialize an array of vector int in C++ with predefined counts?

This creates a vector containing 10 vector<int>, each one of those with 5 elements:

std::vector<std::vector<int>> v(10, std::vector<int>(5));

Note that if the size of the outer container is fixed, you might want to use an std::array instead. Note the initialization is more verbose:

std::array<std::vector<int>, 10> v{{std::vector<int>(5), 
std::vector<int>(5),
std::vector<int>(5),
std::vector<int>(5),
std::vector<int>(5),
std::vector<int>(5),
std::vector<int>(5),
std::vector<int>(5),
std::vector<int>(5),
std::vector<int>(5)
}};

Also note that the contents of array are part of the array. It's size, as given by sizeof, is larger than the vector version, and there is no O(1) move or swap operation available. An std::array is akin to a fixed size, automatic storage plain array.

Note also that, as @chris suggests in the comments, you can chose to set the elements of the array after a default initialization, e.g. with std::fill if they are all to have the same value:

std::array<std::vector<int>, 10> v; // default construction
std::fill(v.begin(), v.end(), std::vector<int>(5));

otherwise, you can set/modify the individual elements:

v[0] = std::vector<int>(5); // replace default constructed vector with size 5 one
v[1].resize(42); // resize default constructed vector to 42

and so on.

How to initialize std::vector from C-style array?

Don't forget that you can treat pointers as iterators:

w_.assign(w, w + len);


Related Topics



Leave a reply



Submit