Pau*_*Sen 6 c++ dictionary stdmap std c++-standard-library
我正在创建一个地图,仅用于学习目的,以存储一些键值对.如果我使用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;
}
Run Code Online (Sandbox Code Playgroud)
取消引用end()是未定义的行为,因为end()将迭代器返回到地图末尾的1.如果你想要最后一个元素,那么你可以使用
p = --arr.end();
Run Code Online (Sandbox Code Playgroud)
你不能使用
p = arr.rbegin()
Run Code Online (Sandbox Code Playgroud)
因为您不能将反向迭代器分配给前向迭代器(实例).如果你想使用rbegin()那么你必须创建一个反向迭代器.
map<int,std::string>::reverse_iterator rit;
rit = arr.rbegin();
// or
auto rit = arr.rebegin(); //C++11 or higher required for this
Run Code Online (Sandbox Code Playgroud)
一如既往,您应该检查以确保您有一个有效的迭代器.如果容器为空begin() == end()并且取消引用任一个未定义的行为.
资料来源:http://en.cppreference.com/w/cpp/container/map/end
要打印最后一个元素,请使用反向迭代器:
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
}
Run Code Online (Sandbox Code Playgroud)
std::map::end将使迭代器返回到过去的最后一个元素,并且取消引用它是未定义的行为。
来自std::map::enden.cppreference
返回容器最后一个元素后面的元素的迭代器。该元素充当占位符;尝试访问它会导致未定义的行为。