Search code examples
c++multimap

c++ multimap, return submap where key is between MIN and MAX


Using c++, i have a multimap. From this multimap i want to get a submap where the keys are withing a MIN and MAX value.

Somthing like :

mmap->insert(1,classInstance); 
mmap->insert(2,classInstance);
mmap->insert(3,classInstance);
mmap->insert(4,classInstance);
mmap->insert(2,classInstance2);
mmap->insert(5,classInstance);
mmap->insert(6,classInstance);

submap = mmap->submap(2,5);

result is a submap with 
2,classInstance
3,classInstance
4,classInstance
2,classInstance2
5,classInstance
as values

How would i achieved this ? Thanks !


Solution

  • You can use class member functions lower_bound and upper_bound.

    Here is a demonstrative program

    #include <iostream>
    #include <map>
    
    struct classInstance {};
    
    int main() 
    {
        std::multimap<int, classInstance> mmap;
    
        mmap.insert( { 1, classInstance() } ); 
        mmap.insert( { 2, classInstance() } );
        mmap.insert( { 3, classInstance() } );
        mmap.insert( { 4, classInstance() } );
        mmap.insert( { 2, classInstance() } );
        mmap.insert( { 5, classInstance() } );
        mmap.insert( { 6, classInstance() } );
    
        auto first = mmap.lower_bound( 2 );
        auto last  = mmap.upper_bound( 5 );
    
        while ( first != last ) std::cout << first++->first << std::endl;
    }
    

    The program output is

    2
    2
    3
    4
    5
    

    The while loop can be substituted for the for loop like

        for ( ; first != last; ++first ) std::cout << first->first << std::endl;