如何获取特定范围内的地图lower_bound?



我想在地图(在一个范围内(中找到我的目标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;
}

主.cpp:29:43:从这里需要/usr/local/Cellar/gcc/7.3.0_1/include/c++/7.3.0/bits/predefined_ops.h:65:22:错误:与"运算符<"不匹配(操作数类型为"std::p air"和"const int"( { return *__it <__val; }

映射的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 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());

看来你的意思是以下几点

#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 表达式。

最新更新