equal_range for a std::multimap

I have a multimap with some keys being duplicates. When I search for a key using equal_range(), I get a pair of iterators back. When the key is duplicate, the iterators are pointing to the first and the last values in the multimap.

If I have code like this -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
std::multimap<string, string> mmap;

mmap.insert(std::pair<string, string>(key1, value1);
mmap.insert(std::pair<string, string>(key2, value2);
mmap.insert(std::pair<string, string>(key2, value3);
mmap.insert(std::pair<string, string>(key3, value4);

std::pair <mmap::iterator, mmap::iterator> ret;
ret = mmap.equal_range(key2);

if(ret.first != ret.second)
{
  // do something
}
else
{
  // do something else
}


Shouldn't key1 and key3 go into else conditional and jusy key2 into the first conditional?

I am seeing even for key1 and key3, it goes into the if conditional.

Can someone point out what I am doing wrong here? Is it not the right way to compare the iterators?
the iterators are pointing to the first and the last values in the multimap
Wrong.
Second iterator is past-the end iterator for returned range. So first and second iterators will be same only if key is not found at all (empty range). To get number of elements found use std::distance(ret.first, ret.second)
Last edited on
Thanks a lot for the clarification. std::distance worked like a charm.
Topic archived. No new replies allowed.