Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memset on vector C++

Tags:

c++

vector

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

like image 938
avd Avatar asked Nov 03 '09 03:11

avd


People also ask

Can I use memset on vector?

Explanation: The memset() in C++ can be used for vectors as mentioned above.

What does memset do in c?

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.

How do you change the size of a vector in C++?

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.


2 Answers

Use std::fill():

std::fill(myVector.begin(), myVector.end(), 0); 
like image 112
Adam Rosenfield Avatar answered Oct 05 '22 13:10

Adam Rosenfield


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.

like image 29
Mark Ransom Avatar answered Oct 05 '22 13:10

Mark Ransom