我想在 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/