Memset on vector C++

Viewed 57792

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.)

5 Answers

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/

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

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