Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在构造要返回的向量时,如何避免额外的复制?_C++_Performance_Vector_Push Back - Fatal编程技术网

C++ 在构造要返回的向量时,如何避免额外的复制?

C++ 在构造要返回的向量时,如何避免额外的复制?,c++,performance,vector,push-back,C++,Performance,Vector,Push Back,这里是C++新手!我写了一个代码,他正在考虑一个由城市构成的世界。这个世界将更新nbTimeStep次。下面是我的代码的大致摘要。为了便于阅读,所有类名都使用大写字母 // Definition of Class `WORLD` class WORLD { private: vector<CITY> cities; public: void AddCity(CITY& city) { cities.push_back(city);

这里是C++新手!我写了一个代码,他正在考虑一个由城市构成的世界。这个世界将更新
nbTimeStep
次。下面是我的代码的大致摘要。为了便于阅读,所有类名都使用大写字母

// Definition of Class `WORLD`
class WORLD
{
  private:
    vector<CITY> cities;
  public:
    void AddCity(CITY& city)
    {
      cities.push_back(city);
    }
}

// In main

WORLD world(Arguments);
for (int time_step=0 ; time_step < nbTimeSteps ; time_step++)
{
   WORLD EmptyWorld;
   world = ReCreateWorld(world,EmptyWorld); // The object `EmptyWorld` will be returned after being 'filled' with cities.
}
在分析之后,我发现大约20%的时间进程都在方法
AddCity
中。我从不需要任何给定城市的两个实例,因此浪费这么多时间复制每个城市似乎很愚蠢我如何绕过这个问题?



有些人可能想评论我将一个空的
世界
传递给
重新创建城市
,因为它不是很优雅。我这样做主要是为了强调慢拷贝部分发生在
cities行重新创建世界
返回其
世界

时,而不是像Justin和Daniel建议的那样,使用move c-tor。传统的方法是使用指针。 typedef std::unique_ptr CITY_ptr; 病媒城市; 只推城市的指针


您可以尝试类似于
emplace
的方法,直接转发c-tor参数。

答案多少取决于
CITY
的外观。是否可以移动它(它是否有移动构造函数)?如果您不确定移动构造函数是什么,
CITY
的移动构造函数将是声明为
CITY(CITY&&)的构造函数,带两个符号。谢谢。也很有帮助。
WORLD& ReCreateWorld(WORLD& OldWorld, WORLD& NewWorld)
{
  for (int city_index=0 ; city_index < NbCities ; city_index++)
  {
    /* Long Process of creating a single 'CITY' called `city`
    ...
    ...
    */


    // Add the city to the list of cities (process I am trying to optimize)
    NewWorld.AddCity(city);
  }
    return NewWorld;
}