![](/img/trans.png)
[英]With a STL map/set/multiset/multimap, How to find the first value greater than or equal to the search key?
[英]Find the first value greater than user specified value from a map container
我有一个地图容器。 如何使用find_if返回大于用户指定搜索值的第一个值,如下所示:
std::map<string, int>::iterator it = find_if(Mymap.begin(), Mymap.end(), ......
非常感谢你!
您确定要对通过容器的值大于您的条件的任何项目进行线性搜索吗?
最好还保留一个单独的排序值索引,您可以将其称为upper_bound
on,以对数时间而不是元素数量为线性。 或者改为查看boost::multi_index
。
用lambda:
int n = MYVALUE;
auto it = std:: find_if(Mymap.begin(), Mymap.end(),
[n](const std::pair<std::string, int> & x) -> bool
{ return x.second > n; }
);
(如果值是固定的,你可以将它直接放在lambda体内。对于C ++ 14及更高版本,lambda捕获可以是[n = MYVALUE]
,你不需要一个单独的外部变量n
。)
带谓词:
struct Finder
{
Finder(int n_) : n(n_) { }
int n;
bool operator()(const std::pair<std::string, int> & x) const
{
return x.second > n;
}
};
auto it = std::find_if(Mymap.begin(), Mymap.end(), Finder(MYVALUE));
对于C ++ 03,您需要提供比较器对象,或者处理一些棘手的绑定:
typedef map<string, int>::value_type Value;
struct Comp
{
Comp(int v) : m_v(v) { }
bool operator()(const Value& v) const
{
return v.second > m_v;
}
int m_v;
};
void f()
{
map<string, int> Mymap;
map<string, int>::iterator it = find_if(Mymap.begin(), Mymap.end(), Comp(42));
}
在STL功能方面,您可能会发现B.Stroustrup这本书非常有用。 他提出了这个代码:
bool gt_42 (const pair <const string ,int>& r )
{
return r.second >42 ;
}
void f (map <string,int >& m )
{
typedef map <string ,int >:: const_iterator MI ;
MI i = find_if (m.begin (), m.end (), gt_42 );
// ...
}
从“The C ++ Programming Language,Special Edition”的“标准库之旅”(可在.pdf文件中获得)中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.