.end()->first 在地图中是什么意思

What is the meaning of .end()->first in maps

考虑这段c++代码。为什么mp.end()->的输出首先是容器中key的个数

#include<iostream>
#include<bits/stdc++.h>

using namespace std;
int main(){
    map<int, char> mp;
    mp[0]='a';
    mp[1]='b';
    mp[2]='c';
    mp[3]='d';
    mp[3]='e';
    mp[7]='f';

    map<int, char>::iterator itr = mp.end();
    cout << itr->first << endl;


    return 0;       
}

此代码的输出是 5

谁能解释一下?

最好的答案可能来自 reference

end() 函数 returns 迭代器越过地图的末尾。取消引用它是未定义的,因此您从这段代码中看到的任何输出都是无关紧要的。

您可能想要做的是查看 end() - 1,在这种情况下,结果将是 intcharstd::pair 给您密钥和地图中该点的值(通过成员 firstsecond)。也看看 that reference

试试这个:

cout << (--itr)->first << endl;

Jon Reeves 所说,使用 iterator 并将其设置为 mapend() 以供以后取消引用是未定义的行为,会给您带来垃圾。实现您想要的也是正确的方法如下:

map<int, char>::reverse_iterator itr = mp.rbegin();
cout << (*itr).first << endl;

这将 return 7。如果您想要字母或 value,请改用 (*itr).second