vendredi 23 juin 2017

iterate over non-const std::unordered_set

I have a std::unordered_set that contains instances of class bar.

I'd like to iterate over all the bars in the set and call some void foo(bar& b) function on each one.

You'll probably notice from the function signature that I want foo to change the state of the bar& b parameter in some way.

Now, I do know that foo won't change bar in a way that affects hashing or equality comparisons, but I still have a problem.

However I iterate over the set, the best I can hope for is a const bar& which obviously won't work.

I can think of a couple of possible ways around this:

  1. Use const_cast. Don't know if this will work (yet). It kind of smells bad to me, but I'm happy to be enlightened!!
  2. Use a std::unordered_map instead of std::unordered_set, so that even if I can only get a const of the key, I can just use that key to lookup the bar object and safely call foo on it.

I'd really appreciate some advice!

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire