C++ vector::clear

后端 未结 6 1089
死守一世寂寞
死守一世寂寞 2020-12-09 09:03
vector  decoy;

void clear_decoy() {  

    decoy.clear();   

    vector (decoy).swap(decoy);  
}

In the above method

6条回答
  •  生来不讨喜
    2020-12-09 09:12

    With clear,

    All the elements of the vector are dropped: their destructors are called, and then they are removed from the vector container, leaving the container with a size of 0.

    Swap just swaps the two vectors,

    Swap content

    Exchanges the content of the vector by the content of vec, which is another vector of the same type. Sizes may differ.

    After the call to this member function, the elements in this container are those which were in vec before the call, and the elements of vec are those which were in this. All iterators, references and pointers remain valid for the swapped vectors.

    It seems you are swapping nothing really and just restores to default allocation. Clear can deallocate but it sometimes does not. You are not only reducing the size but lessening the space allocated with the swap statement.

提交回复
热议问题