Memset on vector C++
Solution 1:
Use std::fill()
:
std::fill(myVector.begin(), myVector.end(), 0);
Solution 2:
If your vector contains POD types, it is safe to use memset on it - the storage of a vector is guaranteed to be contiguous.
memset(&vec[0], 0, sizeof(vec[0]) * vec.size());
Edit: Sorry to throw an undefined term at you - POD stands for Plain Old Data, i.e. the types that were available in C and the structures built from them.
Edit again: As pointed out in the comments, even though bool
is a simple data type, vector<bool>
is an interesting exception and will fail miserably if you try to use memset on it. Adam Rosenfield's answer still works perfectly in that case.
Solution 3:
You can use assign
method in vector:
Assigns new contents to the vector, replacing its current contents, and modifying its size accordingly(if you don't change vector size just pass vec.size() ).
For example:
vector<int> vec(10, 0);
for(auto item:vec)cout<<item<<" ";
cout<<endl;
// 0 0 0 0 0 0 0 0 0 0
// memset all the value in vec to 1, vec.size() so don't change vec size
vec.assign(vec.size(), 1); // set every value -> 1
for(auto item:vec)cout<<item<<" ";
cout<<endl;
// 1 1 1 1 1 1 1 1 1 1
Cited: http://www.cplusplus.com/reference/vector/vector/assign/