Koszuta
Koszuta

Reputation: 37

Understanding vector initialization in C++

If I've got a constructor with an initialization list as such:

std::vector<int> _list;  

Program::Program() : _list(0)
{
}  

Does this initialize all values to 0 even when the vector resizes itself?

Upvotes: 0

Views: 150

Answers (2)

David Scarlett
David Scarlett

Reputation: 3341

You seem to be misunderstanding the argument of the vector constructor that you're calling. _list(0) will initialise _list to length zero, using the default value for type int, which also happens to be zero, but which is irrelevant if the vector doesn't contain any elements. It doesn't explicitly set element values to zero. Perhaps you meant to have the constructor repeats a single value a specified number of times? If so, you need to pass the desired length as the first argument, and the value to repeat for its second argument. This construction does not affect an subsequent resizing to expand the vector, which will populate the new vector elements with the default value (or a different value if you specify one as an additional argument to vector::resize).

Here's an example to illustrate, based on your code, which first initialises the vector with the value 10 repeating for length 5, and then resizes the vector to length 10.

#include <iostream>
#include <vector>

class Program
{
public:
    Program() : _list(0) { }
    Program(unsigned long size, int value) : _list(size, value) { }

    void ResizeList(unsigned long size)
    {
        _list.resize(size);
    }

    void PrintList() const
    {
        std::cout << "_list = ";
        for (const auto& val : _list)
        {
            std::cout << val << ", ";
        }
        std::cout << std::endl;
    }

private:
    std::vector<int> _list;
};

int main()
{
    Program p(5, 10);
    p.PrintList();

    p.ResizeList(10);
    p.PrintList();

    return 0;
}

Output:

_list = 10, 10, 10, 10, 10, 
_list = 10, 10, 10, 10, 10, 0, 0, 0, 0, 0,

Upvotes: 1

Jeffrey Cash
Jeffrey Cash

Reputation: 1073

If you look at the documentation for the std::vector constructor, you'll see that for constructor (3), the one you're using, you'll see that you're constructing 0 elements of type int in-place in _list. This means that you're essentially doing nothing.

When the vector is resized, the elements that space is allocated for will be uninitialized, unless you use the resize function, in which case the elements will be initialized to their default value, or a value of your choice.

For example, if your vector were empty and you did _list.resize(10);, _list would now contain 10 elements of the default-constructed type of int, which should just be 0. If you instead did something like _list.resize(10, 5);, _list would now contain 10 5s.

I hope this helped clear things up for you. If you have any follow up questions, feel free to ask.

Upvotes: 0

Related Questions