Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get second field of map using end()

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;

}
like image 929
Paul Sen Avatar asked Jul 09 '15 12:07

Paul Sen


3 Answers

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.

like image 23
Mohit Jain Avatar answered Sep 21 '22 23:09

Mohit Jain


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

like image 135
NathanOliver Avatar answered Sep 17 '22 23:09

NathanOliver


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.

like image 23
NO_NAME Avatar answered Sep 17 '22 23:09

NO_NAME