如何获得特定范围内的地图的Lower_bound?

问题描述 投票:0回答:2

我想在地图上(在一定范围内)找到目标的下界线。

我知道另一种解决方案:

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

c++ stl lower-bound
2个回答
0
投票
映射的value_typestd::pair<const Key,Value>,因此您需要提供这样的一对作为参数。

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

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

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

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


0
投票
看来您是说以下

#include <iostream> #include <map> #include <iterator> #include <algorithm> int main() { std::map<int, int> m = { { 2, 2 }, { 4, 4 }, { 6, 6 }, { 8, 8 }, { 10, 10 }, { 10, 11 }, { 12, 12 } }; 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, 10 } { 10, 10 }

即在标准算法std::lower_bound中,您可以使用lambda表达式。
© www.soinside.com 2019 - 2024. All rights reserved.