Q:

How to find all keys in map in C++11 which are equal or higher than KEY_1 and lower than KEY_2?

How do I find all keys in map in C++11 which are equal or higher than KEY_1 and lower than KEY_2?
I usually program in Java and don't have much experience in C++.

A:

Try the following
auto minmax = std::minmax( KEY_1, KEY_2, m.key_comp() );

auto first = m.lower_bound( minmax.first );
auto last  = m.upper_bound( minmax.second );

Here is a demonstrative program:
#include <iostream>
#include <map>
#include <algorithm>

int main() 
{
    std::map<int, int> m = 
    { 
        { 1, 10 }, { 2, 20 }, { 3, 30 }, {4, 40 }, { 5, 50 }, { 6, 60 }, { 7, 70 }
    };

    int key1 = 5;
    int key2 = 3;

    auto minmax = std::minmax( key1, key2, m.key_comp() );

    auto first = m.lower_bound( minmax.first );
    auto last = m.upper_bound( minmax.second );

    for ( auto current = first; current != last; ++current )
    {
        std::cout << "{ " << current->first
                  << ", " << current->second
                  << " }" << std::endl;
    }

    return 0;
}

The output is
{ 3, 30 }
{ 4, 40 }
{ 5, 50 }

Or a more interesting example
#include <iostream>
#include <map>
#include <algorithm>
#include <functional>

int main() 
{
    std::map<int, int> m1 = 
    { 
        { 1, 10 }, { 2, 20 }, { 3, 30 }, { 4, 40 }, { 5, 50 }, { 6, 60 }, { 7, 70 }
    };

    int key1 = 5;
    int key2 = 3;

    auto minmax1 = std::minmax( key1, key2, m1.key_comp() );

    auto first1 = m1.lower_bound( minmax1.first );
    auto last1  = m1.upper_bound( minmax1.second );

    for ( auto current = first1; current != last1; ++current )
    {
        std::cout << "{ " << current->first
                  << ", " << current->second
                  << " }" << std::endl;
    }

    std::cout << std::endl;

    std::map<int, int, std::greater<int>> m2 = 
    { 
        { 1, 10 }, { 2, 20 }, { 3, 30 }, { 4, 40 }, { 5, 50 }, { 6, 60 }, { 7, 70 }
    };

    auto minmax2 = std::minmax( key1, key2, m2.key_comp() );

    auto first2 = m2.lower_bound( minmax2.first );
    auto last2  = m2.upper_bound( minmax2.second );

    for ( auto current = first2; current != last2; ++current )
    {
        std::cout << "{ " << current->first
                  << ", " << current->second
                  << " }" << std::endl;
    }

    return 0;
}

The output is
{ 3, 30 }
{ 4, 40 }
{ 5, 50 }

{ 5, 50 }
{ 4, 40 }
{ 3, 30 }

If you want to exclude the upper bound from the range then you have to substitute the call of method upper_bound to lower_bound that is the code will contain two calls of lower_bound with corresponding keys. For example
auto first1 = m1.lower_bound( minmax1.first );
auto last1  = m1.lower_bound( minmax1.second );

If you want to exclude lower bound from the range then you can write
auto first1 = m1.upper_bound( minmax1.first );
auto last1  = m1.upper_bound( minmax1.second );

