std::map<char,int> dict;
...
auto pmax = dict.begin(); // here i get const iterator
Run Code Online (Sandbox Code Playgroud)
我可以“明确指出”获得的值是非常量类型吗?
小智 1
查看您的代码,您基本上正在实现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;
Run Code Online (Sandbox Code Playgroud)
不可否认,这decltype(*begin(dict))是丑陋的,希望可以通过 C++1y 中的泛型 lambda 来弥补。
关键是,无论您是否有 amap::iterator或者map::const_iterator当您取消引用它时,结果都将是 astd::pair并作为const key_type第一个参数。因此,即使您有两个iterator可变it1, it2数据(例如,通过 获取map::begin()),您也无法重新分配pair这些迭代器引用的完整数据。因此,*it1 = *it2不会工作,因为您试图覆盖mapped_type 和const key_type。
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           7988 次  |  
        
|   最近记录:  |