Reputation: 4125
I have defined:
const vector<vector<int>> *ElementLines::Quad4 = new vector<vector<int>>
{
{ 0, 1 },
{ 1, 2 },
{ 2, 3 },
{ 3, 0 }
};
Later on, I want to iterate over that collection, to which an object is pointing:
for (int j = 0; j < e->LinesIndices->size(); j++)
{
int n1Index = e->LinesIndices[j][0]; //I expect 0 (for j = 0)
int n2Index = e->LinesIndices[j][1]; //I expect 1 (for j= 0)
}
The code above won't compile:
no suitable conversion function from "const std::vector<int, std::allocator<int>>" to "int" exists
But if I add LinesIndices[j][0][0]
it indeed delivers an int. I don't quite understand what is happening here. To access a vector I just use one pair of square brackets [i]
, is it different for this nested vector of vectors? (I would expect to be able accessing the contents by using two pairs of square brackets).
Upvotes: 0
Views: 1858
Reputation: 6317
Your code is not compiling because your e->LinesIndices
is a vector<vector<int>>*
(i.e. a pointer).
In C++, as in C, you can use array notation on pointers—a[index]
is equivalent to *(a + index)
. If your pointer pointed to the first element of an array, that is exactly how you would use that array. Unfortunately for you, you only have a single vector allocated via new
. Accessing that pointer via e->LinesIndices[j]
is a Very Bad Thing if j
is not 0 (because you access a vector where there is no actual vector).
There is two ways to fix this. If you really want to keep your vector on the heap, allocated via new
(I hope you delete
it at some point!), you could dereference the pointer before accessing it:
for (int j = 0; j < e->LinesIndices->size(); j++)
{
int n1Index = (*e->LinesIndices)[j][0];
int n2Index = e->LinesIndices[0][j][1]; // This would work too, but I wouldn't recommend it
}
However, the data in your vector is already on the heap. Allocating a std::vector
via new
is something that is—in my personal experience—very rarely necessary, and if it is not necessary for you to have a pointer here (which will heavily depend on the context you use it in), I would suggest directly creating the vector (with no pointer). If you choose this method, you will need to use e->LinesIndices.size()
instead of e->LinesIndices->size()
.
Upvotes: 5