How get non-const iterator

不打扰是莪最后的温柔 提交于 2019-12-23 13:11:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!