Is there any equivalent f开发者_C百科unction 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.)
Use std::fill()
:
std::fill(myVector.begin(), myVector.end(), 0);
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.
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/
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.
m= Number of Rows && n== Number of Columns
vector<vector<int>> a(m,vector<int>(n,0));
精彩评论