Memset on vector C++

C++Vector

C++ Problem Overview


Is there any equivalent function of memset for vectors in C++ ?

(Not clear() or erase() method, I want to retain the size of vector, I just want to initialize all the values.)

C++ Solutions


Solution 1 - C++

Use std::fill():

std::fill(myVector.begin(), myVector.end(), 0);

Solution 2 - C++

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 - C++

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/

Solution 4 - C++

Another way, I think I saw it first in Meyers book:

// Swaps with a temporary.
vec.swap( std::vector<int>(vec.size(), 0) );

Its only drawback is that it makes a copy.

Solution 5 - C++

m= Number of Rows && n== Number of Columns

vector<vector<int>> a(m,vector<int>(n,0));        

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionavdView Question on Stackoverflow
Solution 1 - C++Adam RosenfieldView Answer on Stackoverflow
Solution 2 - C++Mark RansomView Answer on Stackoverflow
Solution 3 - C++JayhelloView Answer on Stackoverflow
Solution 4 - C++Tim FinerView Answer on Stackoverflow
Solution 5 - C++sakigoView Answer on Stackoverflow