通过移动将向量附加到另一个向量(pre C++11)
Append vector to another with a move (pre C++11)
我正在处理一些相对较大的整数向量,我有一个顶级向量,我需要将其他(临时)向量的结果累积到其中。
遗憾的是,将其扩展到原地不是一种选择,因为我从另一个 API 收到预先准备好的临时向量,并且出于同样的原因,我被困在 GCC 4.1.2 上,所以没有一个好的移动语义或 std::move 的 C++11。
目前我正在使用插入进行复制,例如:
vector<int> accumulator;
for(){
vector<int> tempVector = vectReturningFunction();
...
if(!tempVector.empty()){
accumulator.insert(accumulator.end(), tempVector.begin(), tempVector.end());
}
}
由于 temp 通常是一次性的,并且数据可能足够大,我希望能够移动而不是复制,但我无法找到一种优雅的方法。
任何解决方案,甚至只是指向有用方向的指针(没有双关语),将不胜感激。我还模糊地记得几年前读过Stroustrup在C++11之前的一个食谱,可以跨STL容器移动,但是现在有太多C++11的东西,没有提供多少搜索。
谢谢。
您也无法在 C++11 中移动矢量内容。移动语义仅适用于向量的元素,但由于元素是int
因此没有任何好处。你想要的是不可能的。但是如果你想避免合并,你可以存储一个向量的向量:
vector< vector<int> > accumulator;
accumulator.reserve(expectedCount); // reserve some space so that you avoid copying contents on vector resizing.
for(/*...*/){
accumulator.resize(accumulator.size()+1); // make space for a new vector
vectReturningFunction().swap(accumulator.back()); // just swap no copy of the vector
}
这完全取决于您想用累加器做什么。如果你真的需要有一个vector<int>
,那么在最后合并向量比一个接一个地附加它们可能仍然更便宜。
避免复制数据(和重新分配)的唯一方法是不带 C++11,是累积到vector<vector<int>>
std::vector<std::vector<int>> accumulator;
for(){
// C++03
accumulator.resize(accumulator.size()+1);
vectReturningFunction().swap(accumulator.back()); // Juraj
if(accumulator.back().empty())
accumulator.resize(accumulator.size()-1);
// C++11
// auto temp = vectReturningFunction();
// if(!temp.empty())
// accumulator.push_back(std::move(temp));
}
相关文章:
- C++从另一个类访问公共静态向量的正确方法是什么
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 将一个向量插入另一个向量的某个位置
- 将指向给定子类的指针从一个向量复制到另一个向量
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 如何在不复制的情况下将一个向量移动到另一个向量中
- 使用 std::transform 将向量向量 (a) 添加到另一个向量向量 (b)
- 如何按另一个向量的方向调整一个向量?
- 将字符向量复制到另一个向量
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 如何避免将向量的完整值复制到另一个容器
- 如何将所有指针从一个向量移动到另一个向量?
- 如何从另一个向量中的另一个第一元素减去向量中的第一元素
- 用一个向量替换另一个向量的方法
- 如何根据另一个向量中给出的索引拆分向量?
- 如何在另一个类中调用类型类的向量?
- 按另一个向量对一个向量进行排序
- 具有多线程支持的 RenderClass,将函数调用推送到向量以在另一个线程上调用
- 如何设置一个 std::vector 与另一个,其中两个是不同类的向量?