构建要返回的向量时如何避免额外复制?
How can I avoid extra copying when constructing a vector to be returned?
这里是 C++ 新手!我写了一个正在考虑 WORLD
的代码,它由 CITIES
的向量组成。这个世界更新 nbTimeStep
次。这是我的代码的粗略摘要。为了便于阅读,所有 class 名称全部大写。
// 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
return 它的 WORLD
.
正如 Justin 和 Daniel 所建议的那样,使用 move c-tor。老派的方法是使用指针,例如
typedef std::unique_ptr CITY_PTR;
std::vector 个城市;
并且只推送城市指针。
您可以尝试类似于 emplace
http://www.cplusplus.com/reference/vector/vector/emplace/ 的方法,它直接转发 c-tor 参数。
这里是 C++ 新手!我写了一个正在考虑 WORLD
的代码,它由 CITIES
的向量组成。这个世界更新 nbTimeStep
次。这是我的代码的粗略摘要。为了便于阅读,所有 class 名称全部大写。
// 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
return 它的 WORLD
.
正如 Justin 和 Daniel 所建议的那样,使用 move c-tor。老派的方法是使用指针,例如 typedef std::unique_ptr CITY_PTR; std::vector 个城市; 并且只推送城市指针。
您可以尝试类似于 emplace
http://www.cplusplus.com/reference/vector/vector/emplace/ 的方法,它直接转发 c-tor 参数。