c++ - 如何连接多个 std::vectors?

标签 c++ vector stdvector

已经有一个关于如何连接两个 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::vectorstd::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/

相关文章:

c++ - GCC 和 ld 找不到导出的符号......但它们在那里

C++ 异常或将参数传递给线程

c++ - 查找在 3D 网格中具有随机点的立方体的角点

r - 计算一个向量值在另一个向量中出现的次数,包括 R 中的不匹配值

c++ - 将结构上无序集中的选定字段存储到 vector

c++ - 如何在每个元素中使用自定义字符串设置 std::vector<std::string>

c++ - STL vector 交换结构 (C++)

c++ - (Mac) 将字符串参数从 VBA 传递到 dylib - 在 C++ 函数中接收到空字符串

c++ - 如何让QtCreator中的应用程序使用KDE oxygen主题?

c++ - 在 vector<int> 中定义的索引处从 vector<string> 中删除一个字符串