views:

38

answers:

1

I have some code that uses an iterator to loop through all elements of an unordered_map, but within that loop there are several other processes where I store iterators to particular elements in the map, and generally do lots of jumping around but not iterating (excluding the outermost iterator).

It seemed to me that it may be more suitable to use a unordered_map::const_reference to an element if I am not actually iterating. Is this true? The only thing preventing me from using const_references is that from my quick google searches they seems very unused by the populace, or at least little discussed.

+1  A: 

Const correctness is one of the keys to C++ programming.
Writing a program and adding const correctness after the fact is very hard (as it cascades through the code) you need to do it upfront.

As such you should prefer to use const_iterators over iterators. But like all things it is a judgment call.

Personally: If I am not going to modify any elements in the container then I would use const_iterators but if there is a possibility of calling a non const method on an object then you have to just use the iterator.

Martin York
But there are also const_iterators. I tried to experiment with using const_references, but I haven't found a way to initialise them without using an iterator
zenna
Sorry missed that: Once you have found the element it may be wise to use the const reference as iterators may become invalidated under certain conditions. Again it is a judgment call depending on your code. Easy to read means easy to maintain and modify. So use the method that makes the code as easy to maintain as possible.
Martin York