简体   繁体   中英

Copy items from one vector to another vector

I'm trying to copy certain items from one vector into another vector which contains shared_ptr objects.

I don't want a reference but a unique copy of that object placed into the other vector. The whole point of this is to fill listEnvironmentStatic with game object and when the game map starts, everything gets copied to listEnvironment for simulations and when the players wants to reset the map, listEnvironment copies everything from listEnvironmentStatic once again and every object is back to its original location.

    this->listEnvironment.insert(this->listEnvironment.end(), this->listEnvironmentStatic.begin(), this->listEnvironmentStatic.end());

using the std::copy and resizing the second vector does't work either.

Look a the following example:

std::vector<std::shared_ptr<Environment>> listEnvironmentStatic;
std::vector<std::shared_ptr<Environment>> listEnvironment;

Now lets say i have a couple of items in listEnvironmentStatic that i want to copy over to listEnvironment (which always contains at least 1 object), how would I do unique copy and still keep the listEnvironmentStatic in case the player wants to restart the map once again?

If you want new instances which are copies from the originating vector, you could use:

for ( const auto& e : listEnvironmentStatic )
    listEnvironment.push_back( std::make_shared<Environment>( *e ) );

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