C++ 如何获得非常量迭代器 std::map dict; ... 自动pmax=dict.begin();//这里我得到常量迭代器

C++ 如何获得非常量迭代器 std::map dict; ... 自动pmax=dict.begin();//这里我得到常量迭代器,c++,c++11,auto,C++,C++11,Auto,我是否可以“明确指出”获得的值是非常量类型?如果您的dict不是const,将返回std::map::iterator。现在,键是const,但值不是 auto应该为您提供一个std::map::iterator;你有相反的证据吗?看看你的,你基本上是在实现std::max\u元素。因此,您可以将最后一行输出改写为: std::map<char,int> dict; ... auto pmax = dict.begin(); // here i get const iterator

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

如果您的
dict
不是
const
,将返回
std::map::iterator
。现在,键是
const
,但值不是

auto
应该为您提供一个
std::map::iterator
;你有相反的证据吗?

看看你的,你基本上是在实现
std::max\u元素。因此,您可以将最后一行输出改写为:

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

std::cout首先,如果您希望它简短,请使用
typedef
为迭代器创建别名,如
typedef std::map::迭代器MCIIT,但不要使用太多的
auto
,除非
dict
是const,否则该代码不会得到const迭代器。只是
pmax->first
是常量,因为这就是地图的工作方式。他们通过键来维持他们的顺序,因此键不能被修改。这里有一个很好的例子说明了编程老师有多糟糕:他们告诉你事情而没有解释。你应该发布一个完整的例子,因为关于你的代码有几个开放的问题。可能重复@ObiSan:Return value of what?我有MSVC 2012,它关于
std::map::begin
返回值的行为是完全正常的。它返回
std::map::iterator
,谁的值类型是
std::pair
。你需要给出一个完整的例子来说明你的问题。@ObiSan,那没用;它忽略了
auto
@ObiSan:描述一下您在代码中遇到的问题也很好。我认为您的问题是,当您取消注释注释注释代码时,
*pmax=p不编译。这个问题在这个答案中得到了解释,我在下面的评论中也解释了你的问题。迭代器不是常量。键值是const。这是地图维持其秩序所必需的。如果迭代器是const,则映射的值也将是const。尝试
pmax->second=10,您将看到它不是。是。对于调试版本,很抱歉。如果我取消注释注释注释代码,我会在“*pmax=p”行中得到错误,就像“l值指向一个对象常量(const)”。
    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;