0

I'm trying to implement my own hash function for a simple object, say a vector of integers :

struct Key
{
  std::vector<int> vec;

  bool operator==(const Key &other) const
  { return (vec == other.vec); }

};

struct KeyHasher
{
  std::size_t operator()(const Key& k) const
  {
    using std::size_t;
    std::size_t res = 0;

    std::vector <int>::iterator i;
    for (i = k.vec.begin(); i != k.vec.end(); ++i)
    {/* hash code */}

    return res;
  }
};

... but I can't iterate over k.vec. The line

        for (i = k.vec.begin(); i != k.vec.end(); ++i)

is rejected by g++ :

'no match for operator=' (operand types are 'std::vector<int>::iterator [...]'

What's going on ? This syntax would be ok in another context : where's my error ?

Community
  • 1
  • 1
suizokukan
  • 1,303
  • 4
  • 18
  • 33

2 Answers2

3

i needs to be const_iterator: k, and therefore k.vec, is const here. (Better still, use auto.)

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
  • Remember that auto is a C++ 11 feature, so if you are using an older compiler then const_iterator will be your only option. –  May 23 '14 at 20:40
  • Indeed, *std::vector ::const_iterator i;* does the trick, thank you. – suizokukan May 24 '14 at 05:42
  • ... or still better *for (auto i = k.vec.begin(); i != k.vec.end(); ++i)* without any other declaration for *i*. – suizokukan May 24 '14 at 07:15
1

try using const_iterator instead of iterator. k is const.

std::vector <int>::const_iterator i;

otherwise you will need to remove the constness...