简体   繁体   中英

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. I have attempted the following approaches: 1. Naive way:

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. 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.

    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.

Rectangular matrices are better stored in a single vector with fancy indexing (eg data.get(i, j) instead of 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++]);});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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