我正在创建一个地图,仅用于学习目的,以存储一些键值对.如果我使用begin()函数打印第二个地图字段,我可以打印地图的第二个字段但是当我尝试使用end()对地图的最后一个元素执行相同操作时,它无法打印第二个字段.以下是我的代码:
#include <iostream>
#include <cstdlib>
#include <map>
#include <string>
#include <stdio.h>
using namespace std;
map<int,std::string> arr;
map<int,std::string>::iterator p;
int main(int argc,char** argv) {
arr[1] = "Hello";
arr[2] = "Hi";
arr[3] = "how";
arr[4] = "are";
arr[5] = "you";
p = arr.begin();
printf("%s\n",p->second.c_str());
p = arr.end();
printf("%s\n",p->second.c_str());
return 0;
}
解决方法
要打印最后一个元素,请使用
reverse iterator:
map< int,std::string>::reverse_iterator p;
p = arr.rbegin();
if( p != arr.rend() ) {
// Do whatever with,it points to the last element
} else {
// map is empty
}
std :: map :: end会将迭代器返回到最后一个元素,并且取消引用它是未定义的行为.
从std::map::end起en.cppreference
Returns an iterator to the element following the last element of the container. This element acts as a placeholder; attempting to access it results in undefined behavior.