简体   繁体   中英

Swap std::vector as function parameter

I would like to swap in an std::vector as a function parameter, so that the vector doesn't have to be copied.

Something like this:

function( std::vector< MyType >().swap( my_vector ) );

Or in my case like this:

std::make_pair( 0, std::vector< MyType >().swap( my_vector ) );

But of course std::vector::swap returns void, not the created vector.

Is there a way to do this?

Use any modern compiler, then you can use std::move , which takes your vector and returns it as an rvalue:

function(std::move(my_vector));

If that's not available to you, you could try something like this:

template<typename T>
T Move(T & val)
{
    T ret;
    ret.swap(val);
    return ret;
}

Let me know if you have any luck with that.

Or, you can swap the vector directly into the pair after its creation:

std::pair<int, std::vector<MyType> > p;
p.second.swap(my_vector);

Though, I guess this won't help you if you need the return value of std::make_pair as an rvalue.

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