I am creating a map just for learning purpose to store some key value pairs. If I print the second field of map using begin()
function I am able to print the second field of map but when I try to do same with last element of map using end()
it is not able to print the second field. Below is my code:
#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;
}
To print the last element, use 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
will return the iterator to one past last element and dereferencing it is undefined behavior.
From std::map::end
at 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.
Dereferencing end()
is undefined behavior as end()
returns an iterator to 1 past the end of the map. If you want the last element then you can use
p = --arr.end();
You cannot use
p = arr.rbegin()
As you cannot assign a reverse iterator to a forward iterator(live example). If you want to use rbegin()
then you have to create a reverse iterator.
map<int,std::string>::reverse_iterator rit;
rit = arr.rbegin();
// or
auto rit = arr.rebegin(); //C++11 or higher required for this
Or you can convert it to a forward iterator using this answer by visitor
As always you should check to make sure that you have a valid iterator. If the container is empty begin() == end()
and dereferencing either is undefined behavior.
Source: http://en.cppreference.com/w/cpp/container/map/end
You can use --arr.end()
or arr.rbegin()
.
arr.end()
returns iterator to the element after the last element. This allows easier writing loops. This element is only for comparing. Dereferencing it is not allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With