lambda表达式中的参数理解

759 阅读1分钟
int main()
{
        std::map<int, std::string> tmp;
        tmp.insert(std::make_pair(20, "jzou"));
        tmp.insert(std::make_pair(10, "jaou"));
        tmp.insert(std::make_pair(80, "jcou"));
        tmp.insert(std::make_pair(40, "jdou"));
 
        auto itr = std::find_if(tmp.begin(), tmp.end(), [](const std::pair<int, std::string> &pair) -> bool {return pair.first > 50;});
        std::cout << itr->second << std::endl;
        return 0;
}

输出结果为:jcou

lambda表达式格式:

[ capture ] ( params ) mutable exception attribute -> ret { body }

这里,capture没有,可以置空,params指的是该匿名函数,即lambda函数所对应的参数位置的函数的参数,在本例中,对应std::find_if的第三个参数:pred,而pred函数的参数即为*first,对应该实例params即为: std::pair<int, std::string>

std::find_if的函数原型为:

template<class InputIterator, class UnaryPredicate>
  InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) return first;
    ++first;
  }
  return last;
}