Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::multimap getting two ranges

I'm using a C++ std::multimap and I have to loop over two different keys. Is there an efficient way to do this other than creating two ranges and looping over those ranges seperately?

This is the way im doing it now:

std::pair<std::multimap<String, Object*>::iterator,std::multimap<String, Object*>::iterator> range;
std::pair<std::multimap<String, Object*>::iterator,std::multimap<String, Object*>::iterator> range2;

// get the range of String key
range = multimap.equal_range(key1);
range2 = multimap.equal_range(key2);

for (std::multimap<String, Object*>::iterator it = range.first; it != range.second; ++it)
{
    ...
}
for (std::multimap<String, Object*>::iterator it2 = range2.first; it2 != range2.second; ++it2)
{
    ...
}
like image 676
Kaiser Wilhelm Avatar asked Sep 07 '11 15:09

Kaiser Wilhelm


People also ask

How is multimap sorted?

Multimap is an associative container that contains a sorted list of key-value pairs, while permitting multiple entries with the same key. Sorting is done according to the comparison function Compare , applied to the keys. Search, insertion, and removal operations have logarithmic complexity.

Is an std multimap sorted?

1) A std::multimap is only ordered by its keys and you can't reorder it after it's built. 2) You couldn't use std::sort for this anyway because it requires random access iterators and std::multimap only provides bidirectional iterators.

How do you access values in a multimap?

We can find all values of a key in Multimap using is member function equal_range(). It accepts the key as an argument and returns a pair of multimap iterator. This returned pair has a range that represents the entries with given key.

How do I delete multimap?

multimap::erase() function is an inbuilt function in C++ STL, which is defined in <map> header file. erase() is used to remove or erase elements from a multimap container. This function can remove or erase the elements by its key, position or the given range.


1 Answers

The code you started with is the most straightforward.

If you'd really like to iterate over two ranges in the same loop, you can create a custom iterator that takes two iterator ranges, iterates over the first until it's done then switches to the second. This is probably more trouble than it's worth, as you'd need to implement all of the iterator members yourself.

Edit: I was overthinking this; it's easy just to modify the two loops into a single one.

for (std::multimap<String, Object*>::iterator it = range.first; it != range2.second; ++it)
{
    if (it == range.second)
    {
        it = range2.first;
        if (it == range2.second)
            break;
    }
    ...
}
like image 86
Mark Ransom Avatar answered Sep 20 '22 13:09

Mark Ransom