Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

c++ - How can I use lambda for container comparison operator ?

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;

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First define the lambda:

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

Then use decltype:

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

Now when you use q2, pass in the function:

q2 myQueue(compareFunc);

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...