Vector Initialization

How to Initialize a Vector in C++

A practical guide to initializing a std::vector in C++: empty vectors, brace lists, set sizes with fill values, copies from ranges, and common mistakes.

On this page
  1. The short answer
  2. Create an empty vector
  3. Initialize with a list of values
  4. Create a vector with a set size
  5. Braces or parentheses?
  6. Copy from another vector, a range, or an array
  7. Replace the values later
  8. Common mistakes
  9. A complete example
  10. Summary

The short answer

Use braces when you know the values, and parentheses when you want a set number of elements. Both forms need #include <vector>.

std::vector<int> primes{2, 3, 5, 7};  // four elements: 2, 3, 5, 7
std::vector<int> zeros(5);            // five elements, all 0
std::vector<int> sevens(4, 7);        // four elements, all 7

The rest of this guide covers each form, the ways to copy a vector, and the mistakes that catch people most often.

Create an empty vector

An empty vector has no elements. It is a good starting point when you plan to add values one at a time:

std::vector<int> scores;   // size() is 0
scores.push_back(90);
scores.push_back(75);      // now holds 90 and 75

Initialize with a list of values

A comma-separated list in braces gives the vector its elements. The version with an equals sign gives the same result:

std::vector<int> primes{2, 3, 5, 7};
std::vector<int> same = {2, 3, 5, 7};

The same form works for other types, such as std::string (add #include <string>):

std::vector<std::string> names{"Ana", "Ben", "Chen"};

Since C++17, you can often leave out the element type and let the compiler deduce it from the list:

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

Create a vector with a set size

Parentheses with a count create that many elements:

std::vector<int> zeros(5);      // 0 0 0 0 0

Every element of a vector created this way gets a value. For int elements, that value is 0. Plain local variables work differently, since they can start with an unknown value. The question of whether plain ints start at 0 is covered in Are ints initialized to 0 in C?

Add a second argument to give every element the same value:

std::vector<int> sevens(4, 7);  // 7 7 7 7

For class types, a count alone creates default-constructed elements. A std::string default-constructs to an empty string:

std::vector<std::string> blanks(3);            // three empty strings
std::vector<std::string> labels(3, "unknown"); // three copies of "unknown"

Braces or parentheses?

This is the most common source of surprise. When the braced list can form a vector of values, braces prefer that meaning. The same number can therefore mean different things:

std::vector<int> a(5);     // five elements, all 0
std::vector<int> b{5};     // one element, holding 5
std::vector<int> c{5, 0};  // two elements: 5 and 0

A simple rule: use parentheses when you mean “this many elements”, and braces when you mean “these exact values”.

Copy from another vector, a range, or an array

Copying a vector copies every element:

std::vector<int> original{1, 2, 3, 4};
std::vector<int> copy = original;   // 1 2 3 4

Changing copy does not change original, because the two vectors hold separate elements.

Two iterators copy a range. The first position is included, and the second is not:

std::vector<int> middle(original.begin() + 1, original.begin() + 3);  // 2 3

A plain C-style array works the same way. Include <iterator> for std::begin and std::end:

#include <iterator>

int values[] = {10, 20, 30};
std::vector<int> fromArray(std::begin(values), std::end(values));  // 10 20 30

Replace the values later

After a vector exists, assign() or an assignment from a braced list replaces its contents:

std::vector<int> v{1, 2, 3};
v = {4, 5};        // now 4 5
v.assign(3, 0);    // now 0 0 0

Common mistakes

Expecting reserve() to add elements. reserve() sets the capacity, which is the room the vector has before it needs more memory. It does not change the size:

std::vector<int> v;
v.reserve(10);     // capacity is at least 10, but size() is still 0
// v[0] = 1;       // undefined behavior: there is no element 0 yet
v.push_back(1);    // fine

Indexing past the end. operator[] does not check the index. Using an index that is out of range is undefined behavior, and an empty vector has no valid index at all. at() checks the index and throws std::out_of_range instead:

std::vector<int> empty;
// empty[0];       // undefined behavior
// empty.at(0);    // throws std::out_of_range

A complete example

#include <iostream>
#include <vector>

int main() {
    std::vector<int> zeros(3);
    std::vector<int> primes{2, 3, 5, 7};

    for (int z : zeros) {
        std::cout << z << ' ';  // 0 0 0
    }
    std::cout << '\n';

    std::cout << primes.size() << '\n';  // 4
}

The output is:

0 0 0
4

Summary

Use braces to list known values, and parentheses with a count for a set number of elements. To build a vector from existing data, copy it or pass an iterator range. Keep the braces trap and the difference between size and capacity in mind.

For how the element count works and how to change it later, read How does size() work in C++? and How do I resize a vector in C++?

Keep exploring

Guides from other topics

All topics →