Pieter
Pieter

Reputation: 32765

Addressing a vector inside vector of vector pointers

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]?

Upvotes: 3

Views: 315

Answers (4)

icecrime
icecrime

Reputation: 76755

Simply (*myHashtable[i])[j]

Upvotes: 3

Crashworks
Crashworks

Reputation: 41394

Try (*(myHashTable[i]))[j].

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

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

vitaut
vitaut

Reputation: 55564

(*myHashtable[i])[j] because [] operator has higher precendence then * operator.

Upvotes: 2

Related Questions