如何使用lambda的容器比较运算符? [英] How can I use lambda for container comparison operator ?

查看:110
本文介绍了如何使用lambda的容器比较运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我将如何使用内置函数或新类作为自定义比较

This is how I would use inbuilt function or new class as a custom comparator

priority_queue< int, vector<int>, greater<int> > third (myints,myints+4);

  // using mycomparison:
  priority_queue< int, vector<int>, mycomparison > q1;
class mycomparison
{ 
public: 
  bool operator() (const int& lhs, const int&rhs) const
  {
     return (lhs<rhs);
  }
};
  typedef priority_queue<int,vector<int>,mycomparison> q2;

但我不知道我是否可以使用lambda函数。

But I wonder if I can use lambda functions there ..

推荐答案

首先定义lambda:

First define the lambda:

auto compareFunc = [](int a, int b) { return a > b; };

然后使用decltype:

Then use decltype:

typedef priority_queue<int, vector<int>, decltype(compareFunc)> q2;

现在,当您使用 q2 函数:

q2 myQueue(compareFunc);

基本上,priority_queue将函数的类型作为第三个模板参数,而构造函数接受一个指针到该函数本身。

Basically, priority_queue takes the type of a function as it's 3rd template argument, while the constructor takes a pointer to that function itself.

这篇关于如何使用lambda的容器比较运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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