5
std::map<char,int> dict;
...
auto pmax = dict.begin(); // here i get const iterator

我可以“明确指出”获得的值是非常量类型吗?

4

2 回答 2

3

如果你dict不是constbegin将返回一个std::map<char,int>::iterator. 现在,键是const,但值不是。

auto应该给你一个std::map<char,int>::iterator;你有相反的证据吗?

于 2013-04-02T07:39:51.283 回答
0

查看您的代码,您基本上是在实施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::iteratormap::const_iterator何时取消引用它,结果都将是std::pairaconst key_type作为第一个参数。因此,即使您有两个可变数据(例如,通过 获取iterator),您也不能重新分配这些迭代器引用的完整数据。因此,将不起作用,因为您正在尝试覆盖.it1, it2map::begin()pair*it1 = *it2mapped_type const key_type

于 2013-04-02T13:57:20.180 回答