【问题标题】:How to get lower_bound for map in a specific range?如何在特定范围内获取地图的下界?
【发布时间】:2019-10-16 12:57:22
【问题描述】:

我想在地图中(在一个范围内)找到我的目标的下界。

我知道另一种解决方案:

int main() {
  map<int,int> m;
  auto it=m.lower_bound(10);
  cout<<it->first<<" "<<it->second<<endl;
  return 0;
}

但是,我想知道如何使用std::lower_bound(m.begin(),m.end(),***)

int main() {
  map<int,int> m;
  auto it=std::lower_bound(m.begin(),m.end(),10);
  cout<<it->first<<" "<<it->second<<endl;
  return 0;
}

main.cpp:29:43: 从这里需要 /usr/local/Cellar/gcc/7.3.0_1/include/c++/7.3.0/bits/predefined_ops.h:65:22:错误:'operator

【问题讨论】:

  • 不清楚范围是多少?
  • 问题是m.begin()是一个指向一对的迭代器。您不能比较整数值的对。

标签: c++ stl lower-bound


【解决方案1】:

地图的value_typestd::pair&lt;const Key,Value&gt;,因此您需要提供这样的一对作为参数。

鉴于您只对关键部分感兴趣,最好使用接受函数对象的std::lower_bound() 的重载:

auto const it = std::lower_bound(m.begin(), m.end(), std::make_pair(10, 0),
                                 [](auto const& a, auto const& b){ return a.first < b.first; });

我相信,通过阅读文档,但尚未确认,我们可以使用地图的比较器:

auto const it = std::lower_bound(m.begin(), m.end(), std::make_pair(10, 0),
                                 m.value_comp());

【讨论】:

    【解决方案2】:

    你的意思好像是下面这个

    #include <iostream>
    #include <map>
    #include <iterator>
    #include <algorithm>
    
    int main() 
    {
        std::map<int, int> m =
        {
            { 2, 1 }, { 4, 2 }, { 6, 3 }, { 8, 4 }, { 10, -1 }, { 10, 0 }, { 12, 2 } 
        };
    
        int key = 10;
    
        auto it = m.lower_bound( key );
    
        std::cout << "{ " << it->first << ", " << it->second << " }\n";
    
        it = std::lower_bound( std::begin( m ), std::end( m ), key,
                               [&]( const auto &p, const auto &value ) { return p.first < value; } );
    
        std::cout << "{ " << it->first << ", " << it->second << " }\n";
    
        return 0;
    }
    

    程序输出是

    { 10, -1 }
    { 10, -1 }
    

    即在标准算法std::lower_bound 中,您可以使用 lambda 表达式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      相关资源
      最近更新 更多