.end()->first在地图中是什么意思
考虑这段c++代码。为什么 mp.end()->first 的输出是容器中的键数。
#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。
有人可以解释一下吗?
回答
最好的答案可能来自参考文献
该end()函数返回一个超过地图末尾的迭代器。取消引用它是未定义的,因此您从这段代码中看到的任何输出都是无关紧要的。
您可能想要做的是查看end() - 1,在这种情况下,结果将是 a std::pairofint并分别char为您提供地图中该点的键和值(通过成员first和second)。也看看那个参考。
试试这个:
cout << (--itr)->first << endl;