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

Ishaan Kanwar picture Ishaan Kanwar · Aug 29, 2018 · Viewed 16.3k times · Source

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.

Answer

R Sahu picture R Sahu · Aug 29, 2018

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