已经有一个问题讨论了如何连接两个向量: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;
}
我已经知道如何避免内部循环(感谢上述帖子),但我相信通过一些std算法的帮助,这可以在一行中完成。
目前我无法使用C++11。但是,如果C++11有任何优势(超过“没有C++11”),我也很感兴趣如何使用它。
编辑:我将尝试重新表达问题,以使其更加清晰。可以通过插入来连接两个向量。对于我的示例,我将使用以下内容:
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(),....);