brettgag
brettgag

Reputation: 211

multi-dimensional vectors and pointers to vectors

I am trying to store pointers to vectors of pointers to vectors in a vector. (I hope that wasn't too mind boggling). Basically, I have a vector and I want to store multiple matrices in it, hence the 3 dimensions. There seems to be a problem with the way I am accessing elements. I don't particuarlily understand the error because the 3rd dimension is a pointer to a vector of ints. I don't think that should change the way you access the ints.

using namespace std;

vector< vector< vector<int>* >* > matrixHolder;

int main() {

    vector< vector<int>* >* a;

    a->push_back(new vector<int>(10, 0));

    matrixHolder.push_back(a);

    matrixHolder[0][0][0] = 5; //Line 34


    return 0;
}

main.cpp:34: error: invalid conversion from ‘int’ to ‘std::vector < int, std::allocator < int> >*’

Upvotes: 0

Views: 1176

Answers (2)

Benjamin Lindley
Benjamin Lindley

Reputation: 103703

matrixHolder[0] is of type vector<vector<int>*>*, a pointer to a vector of pointers to a vector of ints.

matrixHolder[0][0] dereferences matrixHolder[0], so it is of type vector<vector<int>*>, a vector of pointers to a vector of ints.

matrixHolder[0][0][0] gets the first element of matrixHolder[0][0], and is of type vector<int>*, a pointer to a vector of ints.

So when you do this:

matrixHolder[0][0][0] = 5;

The error is exactly as described by your compiler, an invalid conversion from int (that's what 5 is) to vector<int>* (that's what matrixHolder[0][0][0] is)

The correct syntax for this terrible abomination is:

(*(*matrixHolder[0])[0])[0] = 5;

Or you could also do this:

matrixHolder[0][0][0][0][0] = 5;

But that is probably confusing as to what is going on, making it look like you have a 5 dimensional array.

By the way, you're wrong. You don't need to use pointers, but I won't try to convince you of that here.

On another note:

a->push_back(new vector<int>(10, 0));

a is an uninitialized pointer, and you just dereferenced it. That's undefined behavior.

Upvotes: 3

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

(For a more well-engineered solution...)

Don't use vector<vector<T>> to store matrices. The usual solution is a single array (e.g., vector<T>), using simple arithmetic to compute offsets (x + width * y for row-major storage):

int main() {
    constexpr int w = 10, h = 10;
    vector<vector<int>> matrixHolder(1, vector<int>(w * h, 0));
    int x = 2, y = 3;
    matrixHolder[0][x + w * y] = 5;
}

Sorry for the C++11 syntax.

Upvotes: 0

Related Questions