Search code examples
c++multimap

multmap equal_range in C++


This example for use of equal_range is offered on the cplusplus.com site:

 int main ()
 {
   std::multimap<char,int> mymm;

   mymm.insert(std::pair<char,int>('a',10));
   mymm.insert(std::pair<char,int>('b',20));
   mymm.insert(std::pair<char,int>('b',30));
   mymm.insert(std::pair<char,int>('b',40));
   mymm.insert(std::pair<char,int>('c',50));
   mymm.insert(std::pair<char,int>('c',60));
   mymm.insert(std::pair<char,int>('d',60));

   std::cout << "mymm contains:\n";
   for (char ch='a'; ch<='d'; ch++)
   {
      std::pair <std::multimap<char,int>::iterator, std::multimap<char,int>::iterator> ret;
      ret = mymm.equal_range(ch);
      std::cout << ch << " =>";
      for (std::multimap<char,int>::iterator it=ret.first; it!=ret.second; ++it)
         std::cout << ' ' << it->second;
      std::cout << '\n';
   }

And the output is said to be:

mymm contains:
a => 10
b => 20 30 40
c => 50 60
d => 60

But isn't this wrong? For 'd' for instance the condition it!=ret.second will immediately fail and the loop will never be executed? Or have I got this wrong? (This matters as I have based some code on this example and on a second look think it's likely to misbehave.)


Solution

  • The second iterator in the range is "one-past-the-end" of where it would be just like the way mymm.end() works. If mymm.begin() and mymm.end() are the same there is nothing in the container. Here, ret.first and ret.second being the same, means there is no element in the resulting range. Since there is one element for 'd', ret.first points to that element and ret.second is the same as mymm.end().