Reputation: 1129
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.)
Upvotes: 0
Views: 636
Reputation: 44278
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.
Upvotes: 3
Reputation: 23237
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()
.
Upvotes: 4