【发布时间】:2015-04-17 04:35:00
【问题描述】:
已经有一个关于如何连接两个向量的问题: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”有任何优势的话)。
编辑:我将尝试重新表述这个问题,以使其更清楚。 连接两个向量可以通过插入来完成。对于我的例子,我会使用这个:
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(),....);
【问题讨论】:
-
看到这个answer by Ben Voigt。
-
@MohitBhasi 这是我提到的另一个问题的副本。也许我应该将标题更改为“如何连接许多 std::vectors”;)
-
总结大小,预留,循环使用范围插入。您无能为力。
-
AClass是否有意返回系数的副本而不是 const 引用,或者这仅仅是由于示例的最小化?