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.
Asked
Active
Viewed 3.1k times
7

Ishaan Kanwar
- 399
- 1
- 4
- 16
-
4Common 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 Answers
32
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
- 204,454
- 14
- 159
- 270