Ddor
Ddor

Reputation: 347

How to move one vector into another vector without copying

I have a large vector<object> created inside a scope that I want to push into a vector residing outside that scope without copying it (since it is very large). Is there a way i can push vector v into vvec without doing a copy as I am doing currently?

std:vector<std::vector<object>> vvec;
{
    std::vector<object> v;
    v.emplace_back(object());
    vvec.push_back(v);
}

Upvotes: 1

Views: 1829

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117856

You could std::move it

std::vector<std::vector<object>> vvec;
{
    std::vector<object> v;
    v.emplace_back(object());
    vvec.push_back(std::move(v));
}

If I mock a class as the following

struct object
{
    object() { std::cout << "default construct\n"; }
    object(object const&) { std::cout << "copy construct\n"; }
    object(object&&) { std::cout << "move construct\n"; }
};

then the above snippet of code now produces the output

default construct
move construct

therefore the inner copy was avoided by the move.

Upvotes: 1

Related Questions