如何在C ++ 11中查找地图中等于或高于KEY_1且低于KEY_2的所有键?

时间:2014-11-01 09:11:53

标签: c++ c++11

如何在C ++ 11中查找地图中等于或高于KEY_1且低于KEY_2的所有键?

我通常使用Java编程,并且在C ++方面没有太多经验。

2 个答案:

答案 0 :(得分:3)

尝试以下

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 );

这是一个示范程序:

#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;
}

输出

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

或者更有趣的例子

#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;
}

输出

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

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

如果要排除范围的上限,则必须将方法upper_bound的调用替换为lower_bound,代码将包含两个lower_bound的调用键。例如

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

如果要从范围中排除下限,则可以编写

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

答案 1 :(得分:1)

使用std::map::lower_bound

// All elements in [KEY1 KEY2 )
auto it1 = m.lower_bound ( KEY_1  ) ;
auto it2 = m.lower_bound(  KEY_2  ) ;

for( auto it = it1 ; it != it2 ; ++it )
{
   // it->first , it->second
}