从地图容器中找到大于用户指定值的第一个值 [英] Find the first value greater than user specified value from a map container

查看:76
本文介绍了从地图容器中找到大于用户指定值的第一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个地图容器.如何使用find_if返回大于用户指定的搜索值的第一个值,如下所示:

I have a map container. How to return the first value greater than the user-specified search value by using find_if as follows:

std::map<string, int>::iterator it = find_if(Mymap.begin(), Mymap.end(), ......

非常感谢!

推荐答案

带有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.)

(If the value is fixed you can put it directly inside the lambda body. For C++14 and later, the lambda capture can be [n = MYVALUE] and you don't need a separate outer variable 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));

这篇关于从地图容器中找到大于用户指定值的第一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆