【发布时间】:2013-07-11 16:11:15
【问题描述】:
用函数返回的向量的内容扩展向量的最佳方法是什么?
我能做到:
std::vector<int> base;
{
std::vector<int> tmp = getVec(); //RVO will make this efficient
base.reserve(base.size() + tmp.size());
base.insert(base.end(), std::make_move_iterator(tmp.begin()), std::make_move_iterator(tmp.end()));
}
但是是否可以在不创建 tmp 的情况下做到这一点?我可以通过引用将 base 传递给 getVec,但我觉得参数应该用于输入,返回值用于输出。理想情况下,我能做到:
base.extend(getVec());
但我看不出如何使用法线向量函数来做到这一点。
【问题讨论】:
-
append(base, getVec());,它有适当的身体来做移动和东西。基本上,将临时std::vector从局部变量移动到参数。
标签: c++ performance c++11 coding-style