c++ - 如何获取特定范围内 map 的lower_bound?

标签 c++ stl lower-bound

我想在 map 中(在一个范围内)找到我的目标的 lower_bound。

我知道另一种解决方案:

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<' 不匹配(操作数类型为'std::pair'和“常量”) { 返回 *__it < __val;

最佳答案

value_type map 的 std::pair<const Key,Value> ,因此您需要提供这样的一对作为参数。

鉴于您只对关键部分感兴趣,最好使用 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; });

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

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

关于c++ - 如何获取特定范围内 map 的lower_bound?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58413890/

相关文章:

c++ - 返回对象列表

c++ - 双向解引用迭代器的返回类型

c++ - C++ lower_bound()搜索最接近目标值的元素

c++ - 如何避免不明确的模板实例化?

c++ - 不同文件之间共享全局变量

C++:函数重新声明是未定义的行为吗?

c++ - 创建不可移动类型的 std::vector

c++ - 下限误差

c++ - 查找 vector 中最接近的值

c++ - 如何模拟 remove_unless