4

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.

Ishaan Kanwar
  • 329
  • 1
  • 2
  • 11
  • 4
    Common misunderstanding about the array: you don't need to have `{0}`, people think that _that's_ the value used, as if writing `{5}` will construct them all to `5`. Just writing `int arr[100] = {};` will default construct them to `0`, providing a single value will construct the first value to that, and the rest to `0` – Tas Aug 29 '18 at 04:36
  • Perhaps a [`std::vector` constructor reference](http://en.cppreference.com/w/cpp/container/vector/vector) might be helpful? – Some programmer dude Aug 29 '18 at 04:37

1 Answers1

25

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
R Sahu
  • 200,579
  • 13
  • 144
  • 260