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.)
Explanation: The memset() in C++ can be used for vectors as mentioned above.
The memset() function sets the first count bytes of dest to the value c . The value of c is converted to an unsigned character. The memset() function returns a pointer to dest . This example sets 10 bytes of the buffer to A and the next 10 bytes to B.
C++ Vector Library - resize() Function The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With