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 ints. 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]?
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: