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

Viewed 25612

In an array we can do int arr[100]={0} ,this initializes all the values in the array to 0. I was trying the same with vector like vector <int> v(100)={0} ,but its giving the error error: expected ‘,’ or ‘;’ before ‘=’ token. Also if we can do this by "memset" function of C++ please tell that solution also.

1 Answers

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
Related