Lecture Notes for CS 509, Advanced Programming II

2 March 2004 - STL Maps


How a map (or other sorted associated container) behaves is undefined when its comparator is not a trichotomy, although at the least you would expect two things which should be considered equal to be found not equal:

$ cat t.cc
#include <map>
#include <iostream>

int main() {
  std::map<int, int> good_map;

  good_map.insert(std::make_pair(1, 1));
  good_map.insert(std::make_pair(1, 1));
  std::cout << "good map size = " << good_map.size() << ".\n";

  std::map<int, int, std::less_equal<int> > bad_map;

  bad_map.insert(std::make_pair(1, 1));
  bad_map.insert(std::make_pair(1, 1));
  std::cout << "bad map size = " << bad_map.size() << ".\n";
  }

$ g++ -o t -ansi -pedantic t.cc

$ ./t
good map size = 1.
bad map size = 2.

$ CC -o t t.cc

$ ./t
good map size = 1.
bad map size = 2.

$ 

Because the (non-trichotomus) map less-than operator <= is true for 1 <= 1, the map does not consider the pairs (1, 1) (1, 1) to be equal and inserts them both.


This page last modified on 12 March 2004.