将项目从一个向量复制到另一个向量

时间:2021-08-15 04:20:49

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

我正在尝试将某个项目从一个向量复制到另一个包含shared_ptr对象的向量中。

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.

我不想要一个引用,但是该对象的唯一副本放在另一个向量中。这一点的重点是用游戏对象填充listEnvironmentStatic,当游戏地图开始时,所有内容都被复制到listEnvironment进行模拟,当玩家想要重置地图时,listEnvironment再次从listEnvironmentStatic复制所有内容,并且每个对象都返回到原来的位置。

    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.

使用std :: copy并调整第二个向量的大小也不起作用。

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?

现在假设我在listEnvironmentStatic中有几个要复制到listEnvironment(它总是包含至少一个对象)的项目,我将如何进行唯一复制并保持listEnvironmentStatic,以防玩家想要重启地图一次再次?

1 个解决方案

#1


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

#1


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