std::map<char,int> dict;
...
auto pmax = dict.begin(); // here i get const iterator
我可以“明确指出”获得的值是非常量类型吗?
如果你dict
不是const
,begin
将返回一个std::map<char,int>::iterator
. 现在,键是const
,但值不是。
auto
应该给你一个std::map<char,int>::iterator
;你有相反的证据吗?
查看您的代码,您基本上是在实施std::max_element
。因此,您可以将最后一个输出行重写为:
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;
诚然,这decltype(*begin(dict))
很丑陋,希望可以通过 C++1y 中的通用 lambda 来弥补。
关键是,无论您是否有 amap::iterator
或map::const_iterator
何时取消引用它,结果都将是std::pair
aconst key_type
作为第一个参数。因此,即使您有两个可变数据(例如,通过 获取iterator
),您也不能重新分配这些迭代器引用的完整数据。因此,将不起作用,因为您正在尝试覆盖和.it1, it2
map::begin()
pair
*it1 = *it2
mapped_type
const key_type