c++stdvectorstdmove

overwrite std::vector<T> with another std::vector<T> efficiently


#include <iostream>
#include <vector>
#include <utility> 

// simple user-defined class
class MyClass {
public:
    MyClass(int val) : value(val) {}

private:
    int value;
};

int main() {
    // Create and initialize sourceVector and destinationVector with MyClass instances
    std::vector<MyClass> sourceVector = {MyClass(1), MyClass(2), MyClass(3)};
    std::vector<MyClass> destinationVector = {MyClass(10), MyClass(20), MyClass(30)};

    // Move elements from sourceVector to destinationVector
    destinationVector = std::move(sourceVector);

    // sourceVector.size() = 0 <-- not good

    return 0;
}

Suppose we have std::vector<T> old and std::vector<T> new, which are guaranteed to have the same size or both are uninitialized. The goal is to do an assignment of the form old = new. After this, I do not care what values new has since I will re-compute it. However, what must be guaranteed is that the size of new is not changed. The operation should be very efficient, so I would like to avoid copying (T may be itself a large object.)

Clearly, std::move does not work because it changes the size of the vector.


Solution

  • std::swap(sourceVector, destinationVector);
    

    or std::ranges::swap(sourceVector, destinationVector); if you feel fancy (which does the same thing).