Reputation: 32765
To implement an open hash table in C++, I thought I'd define a vector that contains pointers to vectors containing data. For the sake of simplicity, let's say I want a hash table that can store int
s. I assumed I needed a vector< vector<int>* >
for that.
The resulting data structure could look something like this:
[index 0] 8, 6, 2
[index 1] (empty)
[index 2] 9, 12, 15, 28, 1
I could have created a static array of vector<int>
pointers, but I wanted to be able to add more indices as I go along.
To write out elements, I wanted to do something like this:
for (unsigned int i = 0; i < myHashtable.size(); i++) {
cout << "[index " << i << "]";
for (unsigned int j = 0; j < myHashtable[i]->size(); j++) {
cout << " " << *(myHashtable[i])[j];
}
cout << "\n";
}
This code doesn't compile. What's the correct way to address *(myHashtable[i])[j]
?
Upvotes: 3
Views: 315
Reputation: 272517
(*myHashtable[i])[j]
Subscript operator ([]
) binds more tightly than dereference (*
) (see http://www.cppreference.com/wiki/operator_precedence). Therefore you need to force the binding by using parentheses.
Incidentally, you could write you inner loop thus:
for (vector<int>::iterator it = myHashtable[i]->begin();
it != myHashtable[i]->end(); ++it)
{
cout << " " << *it;
}
Upvotes: 7
Reputation: 55564
(*myHashtable[i])[j]
because []
operator has higher precendence then *
operator.
Upvotes: 2