问题
std::map<char,int> dict;
...
auto pmax = dict.begin(); // here i get const iterator
Can I "explicitly indicate" that the value obtained is a non-constant type?
回答1:
Looking at your code, you are basically implementing std::max_element. So you could rewrite your last output line to:
std::cout << std::max_element(begin(dict), end(dict),
[](decltype(*begin(dict)) a, decltype(*begin(dict)) b) {
return a.second < b.second;
})->first << std::endl;
Admittedly, the decltype(*begin(dict)) is ugly, which hopefully will be remedied by generic lambdas in C++1y.
The point is, that regardless of whether you have a map::iterator or map::const_iterator when you dereference it, the result will be a std::pair with a const key_type as first argument. So, even if you have two iterators it1, it2 to mutable data (e.g., acquired via map::begin()), you can not re-assign the complete pair that is referenced by those iterators. Thus, *it1 = *it2 won't work, because you are trying to overwrite the mapped_type and the const key_type.
回答2:
If your dict is not const, begin will return a std::map<char,int>::iterator. Now, the key is const, but the value is not.
auto should give you a std::map<char,int>::iterator; do you have evidence to the contrary?
来源:https://stackoverflow.com/questions/15758629/how-get-non-const-iterator