Memset on vector C++

后端 未结 4 1251
半阙折子戏
半阙折子戏 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 04:49

    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/

    0 讨论(0)
  • 2020-12-13 04:56

    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.

    0 讨论(0)
  • 2020-12-13 04:59

    Use std::fill():

    std::fill(myVector.begin(), myVector.end(), 0);
    
    0 讨论(0)
  • 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<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.

    0 讨论(0)
提交回复
热议问题