Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Vector of vectors

Tags:

c++

vector

I have a class header file called Grid.h that contains the following 2 private data object:

vector<int> column;
vector<vector<int>> row;

And a public method whose prototype in Grid.h is such:

int getElement (unsigned int& col, unsigned int& row);

The definition of above mentioned function is defined as such in Grid.cpp:

int getElement (unsigned int& col, unsigned int& row)
{
    return row[row][col] ;
}

When I run the program, I get this error:

error C2109: subscript requires array or pointer type

Whats going wrong?

like image 229
xbonez Avatar asked Apr 26 '10 22:04

xbonez


People also ask

Can you have a vector of vectors?

Yes! Yes, you can make a vector of vectors in C++. The normal vector is a one-dimensional list data structure. A vector of vectors is a two-dimensional list data structure, from two normal vectors.

Can you have a vector in a vector C++?

A two-dimensional vector in C++ is just a vector of vectors. For example, you could define a two-dimensional vector of integers as follows: vector<vector<int> > v2; Note the space between <int> and the second >.


1 Answers

In the line return row[row][col]; the first row is the int&, not the vector.

The variable declared in the inner scope is shadowing the variable in the outer scope, so the compiler is trying to index an int rather than a vector, which it obviously can't do.

You should fix your variable names so that they don't conflict.

EDIT: Also, while the error that you're getting indicates that the compiler is finding the wrong row variable, as A. Levy points out, you also have a problem with the declaration of your vector, so even if you fix the variable names, if you have indeed declared the vector as shown here, it won't compile. Nested templates need spaces between the > symbols, otherwise the compiler will read >> as a right-shift operator rather than part of a template declaration. It needs to be

std::vector<std::vector<int> > row;

or

std::vector< std::vector<int> > row;

In addition, as you're doing this in a header file, you're going to need to tack the std:: tag on the front of anything from the std namespace - such as vector. If it were in a cpp file, then you could use using namespace std; but that would be very bad to do in a header file (since it would pollute the global namespace). Without the std:: tag or the using statement, the compiler won't recognize vector.

like image 61
Jonathan M Davis Avatar answered Oct 12 '22 05:10

Jonathan M Davis