已经有一个关于如何连接两个 vector 的问题:Concatenating two std::vectors .但是,我发现开始一个新问题是合适的,因为我的问题更具体一些......
我有两个看起来像这样的类:
class AClass {
public:
std::vector<double> getCoeffs() {return coeffs;}
private:
std::vector<double> coeffs;
};
class BClass {
public:
std::vector<double> getCoeffs() {return ...;}
private:
std::vector<AClass> aVector;
};
连接 aVector 中每个元素的系数的最佳方法是什么(即避免不必要的复制等)?
我的第一次尝试是
std::vector<double> BClass::getCoeffs(){
std::vector<double> coeffs;
std::vector<double> fcoefs;
for (int i=0;i<aVector.size();i++){
fcoefs = aVector[i].getCoeffs();
for (int j=0;j<fcoefs.size();j++{
coeffs.push_back(fcoefs[j]);
}
}
return coeffs;
}
我已经知道如何避免内部 for 循环(感谢上面提到的帖子),但我很确定,在一些标准算法的帮助下,这可以在一行中完成。
我目前无法使用 C++11。尽管如此,我也对如何在 C++11 中做到这一点感兴趣(如果与“无 C++11”相比有任何优势)。
编辑:我会试着改写一下这个问题,让它更清楚。 连接两个 vector 可以通过插入来完成。对于我的例子,我会使用这个:
std::vector<double> BClass::getCoeffs(){
std::vector<double> coeffs;
std::vector<double> fcoefs;
for (int i=0;i<aVector.size();i++){
fcoefs = aVector[i].getCoeffs();
coeffs.insert(coeffs.end(),fcoefs.begin(),fcoefs.end());
}
return coeffs;
}
是否可以避免 for 循环? 我可以想象可以写出类似的东西
for_each(aVector.begin(),aVector.end(),coeffs.insert(coeffs.end(),....);
最佳答案
您可以在 C++11 中执行此操作:
std::for_each(aVector.begin(), aVector.end(), [&](AClass i){const auto& temp = i.getCoeffs(); coeffs.insert(coeffs.end(), temp.begin(), temp.end());});
C++03 更难,因为它缺少 lambda 和 bind
.
尽可能好的做法是在内部循环中使用复制:
for(std::vector<AClass>::iterator it = aVector.begin(); it != aVector.end(); ++it){
const std::vector<double>& temp = it->getCoeffs();
coeffs.insert(coeffs.end(), temp.begin(), temp.end());
}
它们本质上是同一件事,尽管您可以通过返回 const std::vector<double>&
来改进两者的运行时间来自 getCoeffs
.
编辑:
Arg,刚看到你添加了insert
你的问题。我以为我真的会在那里帮助你。作为一个安慰提示,你在这里真正问的是展平 std::vector
的 std::vectors
.那有一个答案 here .但是如果你有机会获得提升,你应该看看:http://www.boost.org/doc/libs/1_57_0/libs/multi_array/doc/reference.html#synopsis
关于c++ - 如何连接多个 std::vectors?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28545273/