With the advent of C ++ 11, we have unordered_map.cbegin / cend to specifically return us const_iterator values. therefore, the deduced type "it" in the expression "auto it = unordered_map.cbegin ()" is const_iterator.
However, when it comes to the unordered_map.find (key) function, I think there may be no "cfind ()" character, which in particular returns const_iterator.
Some say that we can use "const auto it = unordered_map.find (key)" to get a "constant iterator", but I have a strong suspicion that the "const iterator" is the same "const_iterator", where " The const iterator "limits the ability to change the iterator itself, and the" const_iterator "limits the ability to change the contents that the iterator refers to.
So, really, if we want to fully use the deduction of type "auto" (with knowledge of the confusion or variations of the "automatic" type of deduction - auto, auto &, const auto &, etc.), how can I get unordered_map.find ( key) to return "const_iterator" without having to explicitly specify "const_iterator" - which, after all the best use case for auto!
The following is a simple code example that demonstrates compiler behavior:
#include "stdafx.h" #include <unordered_map> int _tmain(int argc, _TCHAR* argv[]) { typedef std::unordered_map<int, int> umiit; umiit umii; auto it0 = umii.find(0); it0->second = 42; const auto it1 = umii.find(0); it1->second = 42; umiit::const_iterator it2 = umii.find(0); it2->second = 42; // expected compiler error: assigning to const return 0; }
source share