【发布时间】:2016-11-02 01:04:11
【问题描述】:
这里是 C++ 新手!我写了一个代码,它正在考虑一个由CITIES 向量组成的WORLD。这个世界会更新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.
}
函数ReCreateWorld定义为
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;
}
分析后,我看到大约 20% 的时间进程在方法 AddCity 中。我从不需要任何给定CITY 的两个实例,因此浪费大量时间复制每个城市似乎很愚蠢。 我该如何解决这个问题?
有些人可能想评论我将一个空的WORLD 传递给ReCreateCities,因为它不是很优雅。我这样做主要是为了强调慢速复制部分发生在cities.push_back(city); 行,而不是ReCreateWorld 返回其WORLD 时。
【问题讨论】:
-
答案在某种程度上取决于
CITY的样子。可以移动吗(是否有移动构造函数)? -
如果您不确定什么是移动构造函数,
CITY的移动构造函数将是一个声明为CITY(CITY&&);的构造函数,带有两个 &。
标签: c++ performance vector push-back