Dynamic names when initializing variables in C++

I'm wondering if there is a way to dynamically name variables - to be more precise; Is there a way to initialize variables in for-loops in such a way that every time the loop executes a part of the name changes? E.g: creating 10 variables with the names row1, row2, row3, row4 [...] row10 - where "row" stays the same but the number at the end changes.

Why I need to know: I'm trying to get my head around two-dimensional vectors and ran into a problem; every row of my vector matrix is a vector with the name "row" and it is therefore not possible to check the length of the rows using the .size method on them (like with the columns) since they don't have unique names.

//Creation of vector
vector <vector <int> > multiVector;    
for (int i = 0; i < 5; i++) { //Vector is given 5 rows
        vector <int> rad (7);
        multiVector.push_back(rad); //The newly declared vector is filled with rows
    }

//Vector is printed
    for (int i = 0; i < multiVector.size(); i++) {
        for (int j = 0; j < 7; j++) {
            cout << multiVector[i][j] << " ";
        }
        cout << endl;
    }

Thank you for your help!

Answers


You can get the size of the ith row by accessing that row and then calling size on it: multiVector[i].size().

And no, you can't dynamically generate variable names. Variable names exist only in source code and at compile-time to assist the programmer and compiler in identifying different variables. They do not exist at run-time, so cannot be generated while the program is running. If you ever think you need variables with increasing numbers after their names, then what you really want is an array.


Need Your Help

How do I center an image horizontally within a div?

alignment center

Here's the code. I can't figure out how to make the image be horizontally centered inside the div. Thanks in advance!

Typescript Error: TS2604 - How to fix?

reactjs typescript redux-form

I am trying to use a library called redux-form in a Typescript based project. When I take their "simple form" example code and implement it I get an error: