Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing a 2D vector using push_back()

I am currently declaring my vector as follows

std::vector<std::vector<int>> test(5, std::vector<int>(2,0));

I then access it like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

`

    for (int i = 0; i < 5; i++) {

        std::cin >> test[i][0];
        std::cin >> test[i][1];
    }

`
Since the vector is static (5 Rows, with 2 columns), I would like to make it variable (rows variable, column staitc) by using push_back. However, I don’t know how to access the individual columns. Maybe someone can help me.

I already tried to access it with
test.at(i).at(0) and
test.at(i).at(1) but it wont work.
Although I found this solution
`

#include <iostream>
#include <vector>
using namespace std;
 
int main() {
    std::vector<std::vector<int> >nns;
int i = 5;
nns.push_back(std::vector<int> {i});
for(int i = 0; i <nns.size(); i++)
{
    for(int j = 0; j < nns[i].size(); j++)
    {
        std::cout << nns[i][j] << std::endl;
    }
}
}

` but there you have to define a static size (int i = 5).

>Solution :

You know how to push a vector into the vector of vectors. You wrote this:

nns.push_back(std::vector<int> {i});

You do not have to specifiy the size i here, you can push an empty vector

nns.push_back({});

Now nns has a single element. nns[0] has 0 elements. Pushing elements to nns[0] works exactly the same, just that its elements are not vectors but integers:

nns[0].push_back(42);      

If you do that m-times then nn[0] will have m elements. Also resize works on the inner as well as on the outer vectors. For example to get n elements (vectors) each with m elements (integers):

nns.resize(n);
for (int i=0; i<nn.size(); ++i) nns[0].resize(m);

TL;DR There is nothing special about nested vectors. The outer vectors work exactly the same as the inner vectors. You can construct them with or without elements and you can push elements or resize them.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading