Phalgun
Phalgun

Reputation: 1494

Strange behavior of upper_bound() in Maps

I wrote a below sample code to understand upper_bound() in Map, however I could not understand the behavior for the below:-

// Sample upper_bound()
#include <iostream>
#include <map>
#include <limits>

int main ()
{
  std::map<unsigned int,int> mymap;
  std::map<unsigned int,int>::iterator itup;

  mymap[0] = 5;
  mymap[5] = 5;
  mymap[10] = 5;
  mymap[15] = 5;
  mymap[20] = 5;
  mymap[25] = 5;
  mymap[30] = 5;

  // print content:
  for (std::map<unsigned int,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
    std::cout << it->first << " => " << it->second << '\n';


  itup=mymap.upper_bound (30);


  std::cout<<"First "<< itup->first<<": Second "<< itup->second<<"\n";

  return 0;
}

From http://en.cppreference.com/w/cpp/container/map/upper_bound,

"Iterator pointing to the first element that is greater than key. If no such element is found, past-the-end (see end()) iterator is returned."

Why does the past-the-end iterator return such values?

Upvotes: 0

Views: 238

Answers (2)

Ami Tavory
Ami Tavory

Reputation: 76297

The following line:

std::cout << std::boolalpha << (mymap.upper_bound(30) == mymap.end()) << std::endl; 

indeed verifies that this is the iterator to end. You are not supposed to dereference this iterator. If you do - all bets are off, and you'll get some result that is unspecified.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477040

Since there is no key strictly greater than 30, itup is the end iterator. You are not allowed to dereference the end iterator, so your program has undefined behaviour.

Upvotes: 1

Related Questions