Memset on vector C++

后端 未结 4 1271
半阙折子戏
半阙折子戏 2020-12-13 04:22

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

(Not clear() or erase() method, I want to retain the size of v

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 05:08

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

提交回复
热议问题