简体   繁体   English

如何在现代C ++中将列附加到2D向量

[英]How to append a column to a 2d vector in modern C++

I am thinking about what's the modern way to append a column to a 2d vector. 我正在考虑将列附加到2d向量的现代方法是什么。 I have attempted the following approaches: 1. Naive way: 我尝试了以下方法:1.天真的方法:

void insert_col(vector<vector<int>>& data, vector<int>& newCol){
    if(newCol.size()!=data.size()){
        return ;
    }
    for(int i = 0; i < data.size(); i++){
        data[i].push_back(newCol[i]);
    }
}

Second attempt that does not work: 第二次尝试不起作用:

transform(data.begin(), data.end(), newCol.begin(), /*not sure about this part*/, [](vector<int>& row, int colVale)->int{return colVale;});

The idea is to use transform to iterate both 2d vector and the column to be inserted. 这个想法是使用transform来迭代2d向量和要插入的列。 I am wondering if there's a way to append at the end of each row? 我想知道是否有一种方法可以在每行的末尾附加?

  1. Third attempt: 第三次尝试:

    reinsert each row into the data.begin() which would work but probably not efficient. 将每一行重新插入到data.begin()中,该方法可以工作,但可能效率不高。

    Any other efficient solution would be highly appreciated. 任何其他有效的解决方案将不胜感激。 Thanks! 谢谢!

You ask for an efficient solution. 您要求一个有效的解决方案。 But you have hobbled performance from the outset by using a naive vector<vector<int>> and storing the data row-wise when you want to append column-wise. 但是,从一开始,通过使用朴素的vector<vector<int>>并在要逐列追加时将数据逐行存储会降低性能。

Rectangular matrices are better stored in a single vector with fancy indexing (eg data.get(i, j) instead of data[i][j] ). 矩形矩阵最好通过花式索引(例如,使用data.get(i, j)代替data[i][j] )存储在单个向量中。 If you store column-wise, appending a column is as simple as: 如果您按列存储,那么添加列很简单:

data.push_back(newCol);

You can just do like this: 您可以这样做:

void insert_col(vector<vector<int>>& data, vector<int>& newCol) {
    data.push_back(newCol);
}

How about this 这个怎么样

//For each vector<int> in the 2d vector, 
//push_back the corresponding element from the newCol vector
for_each(data.begin(), data.end(), [&i, &newCol](vector<int>& v){v.push_back(newCol[i++]);});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM