开发者

const_reference or iterator for map (when not actually iterating)

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::c开发者_Python百科onst_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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜