0

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.)

1
  • Iterator intervals are half-open. Commented Jun 26, 2014 at 20:52

2 Answers 2

4

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().

Sign up to request clarification or add additional context in comments.

1 Comment

cheers. Sadly that rules out one reason why my code was misbehaving :(
3

No, it is not wrong. According to

Returns a range containing all elements with the given key in the container. The range is defined by two iterators, one pointing to the first element that is not less than key and another pointing to the first element greater than key.

from http://en.cppreference.com/w/cpp/container/multimap/equal_range it works as expected.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.