简体   繁体   中英

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM