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

问题描述

考虑这段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

enter image description here

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

您可能想要做的是查看 end() - 1,在这种情况下,结果将是 std::pairintchar 为您提供键和值分别在地图中的那个点(通过成员 firstsecond)。也看看 that reference

试试这个:

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

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

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

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