Rocking chief
Rocking chief

Reputation: 1069

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!

Upvotes: 1

Views: 3748

Answers (3)

gchen
gchen

Reputation: 1173

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++]);});

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249123

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 (e.g. 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);

Upvotes: 2

Mohit
Mohit

Reputation: 1275

You can just do like this:

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

Upvotes: 0

Related Questions