lll
lll

Reputation: 332

concatenate 2D vector to the left

When left and right are:

vector<vector<int>> left = {{10, 20}, {30, 40}}; 
vector<vector<int>> right = {{1, 2}, {3, 4}};

I want my leftRight vector to be:

vector<vector<int> leftRight = {{10, 20, 1, 2}, {30, 40, 3, 4}}

This is what I tried but doesn't work:

#include <vector>
using namespace std; 

int main() 
{ 
    vector<vector<int>> left = {{10, 20}, {30, 40}}; 
    vector<vector<int>> right = {{1, 2}, {3, 4}};
    vector<vector<int>> leftRight;

    leftRight.reserve(left.size());
    for(int i = 0; i < left.size(); i++) { 
    leftRight[i].reserve(left[i].size() + right[i].size()); 
    leftRight[i].insert(leftRight[i].end(); left[i].begin(), left[i].end());
    leftRight[i].insert(leftRight[i].end(); right[i].begin(), right[i].end());
    }
    return 0; 
}

Upvotes: 1

Views: 93

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

There is a typo in these statements

leftRight[i].insert(leftRight[i].end(); left[i].begin(), left[i].end());
                                     ^^^
leftRight[i].insert(leftRight[i].end(); right[i].begin(), right[i].end());
                                     ^^^

Use a comma instead of the semicolon.

And you may not use the subscript operator for an empty vector.

So you should write

leftRight.resize(left.size());

instead of

leftRight.reserve(left.size());

Here is an updated your program

#include <iostream>
#include <vector>

using namespace std; 

int main() 
{ 
    vector<vector<int>> left = {{10, 20}, {30, 40}}; 
    vector<vector<int>> right = {{1, 2}, {3, 4}};
    vector<vector<int>> leftRight;

    leftRight.resize(left.size());
    for(int i = 0; i < left.size(); i++) { 
    leftRight[i].reserve(left[i].size() + right[i].size()); 
    leftRight[i].insert(leftRight[i].end(), left[i].begin(), left[i].end());
    leftRight[i].insert(leftRight[i].end(), right[i].begin(), right[i].end());
    }

    for ( const auto &v : leftRight )
    {
        for ( const auto &item : v ) std::cout << item << ' ';
        std::cout << '\n';
    }       

    return 0; 
}

Its output is

10 20 1 2 
30 40 3 4 

Upvotes: 3

Nico Schertler
Nico Schertler

Reputation: 32587

leftRight.reserve(left.size());

This will only reserve the space but does not actually create elements. Therefore, accessing any leftRight[i] will fail.

You want

leftRight.resize(left.size());

Upvotes: 1

Related Questions