First define the lambda object, then pass it to the template's type using decltype and also pass it directly to the constructor.

auto comp = []( adjist a, adjlist b ) { return a.second > b.second; };
priority_queue< adjlist_edge , vector<adjlist_edge>, decltype( comp ) >
     adjlist_pq( comp );
Answer from Potatoswatter on Stack Overflow
🌐
Walletfox
walletfox.com › course › sortvectorofcustomobjects11.php
How to use lambda expression to sort a vector of custom objects (since C++11)
We initialize our vector of four Skyscraper objects and define a lambda expression sortRuleLambda with references to two Skyscraper objects passed as arguments, bool as a return type and no captures. The body of the lambda expression performs the comparison and returns the result.
Top answer
1 of 7
46

It's unlikely that the compiler will be able to inline a std::function call, whereas any compiler that supports lambdas would almost certainly inline the functor version, including if that functor is a lambda not hidden by a std::function.

You could use decltype to get the lambda's comparator type:

#include <set>
#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
   auto comp = [](int x, int y){ return x < y; };
   auto set  = std::set<int,decltype(comp)>( comp );

   set.insert(1);
   set.insert(10);
   set.insert(1); // Dupe!
   set.insert(2);

   std::copy( set.begin(), set.end(), std::ostream_iterator<int>(std::cout, "\n") );
}

Which prints:

1
2
10

See it run live on Coliru.

2 of 7
29

Yes, a std::function introduces nearly unavoidable indirection to your set. While the compiler can always, in theory, figure out that all use of your set's std::function involves calling it on a lambda that is always the exact same lambda, that is both hard and extremely fragile.

Fragile, because before the compiler can prove to itself that all calls to that std::function are actually calls to your lambda, it must prove that no access to your std::set ever sets the std::function to anything but your lambda. Which means it has to track down all possible routes to reach your std::set in all compilation units and prove none of them do it.

This might be possible in some cases, but relatively innocuous changes could break it even if your compiler managed to prove it.

On the other hand, a functor with a stateless operator() has easy to prove behavior, and optimizations involving that are everyday things.

So yes, in practice I'd suspect std::function could be slower. On the other hand, std::function solution is easier to maintain than the make_set one, and exchanging programmer time for program performance is pretty fungible.

make_set has the serious disadvantage that any such set's type must be inferred from the call to make_set. Often a set stores persistent state, and not something you create on the stack then let fall out of scope.

If you created a static or global stateless lambda auto MyComp = [](A const&, A const&)->bool { ... }, you can use the std::set<A, decltype(MyComp)> syntax to create a set that can persist, yet is easy for the compiler to optimize (because all instances of decltype(MyComp) are stateless functors) and inline. I point this out, because you are sticking the set in a struct. (Or does your compiler support

struct Foo {
  auto mySet = make_set<int>([](int l, int r){ return l<r; });
};

which I would find surprising!)

Finally, if you are worried about performance, consider that std::unordered_set is much faster (at the cost of being unable to iterate over the contents in order, and having to write/find a good hash), and that a sorted std::vector is better if you have a 2-phase "insert everything" then "query contents repeatedly". Simply stuff it into the vector first, then sort unique erase, then use the free equal_range algorithm.

🌐
Codeforces
codeforces.com › blog › entry › 92918
[Tutorial] Sorting with lambda - Codeforces
For example, one array could contain a value of a cell and the other one — it's color. Say that we want to simultaneously sort both those arrays by value (increasing). In order to do that, we may rather introduce a new array, order, which will at first contain numbers from 0 to n - 1. We now simply sort according to the following lambda: sort(order.begin(), order.end(), [&values](int a, int b) { return values[a] < values[b]; });.
🌐
Study Plan
studyplan.dev › pro-cpp › lambda › q › lambda-as-comparator
Using Lambdas as Comparators | Lambdas | StudyPlan.dev
October 11, 2022 - Here, std::sort is called with ... a comparator. The comparator is a lambda that takes two Player objects and returns true if the first player's score is less than the second player's score....
🌐
Medium
ayanc.medium.com › passing-custom-parameter-in-c-custom-comparator-81e4daaf25a4
Passing Custom Parameter in C++ Custom Comparator | by Ayan Chowdhury | Medium
July 23, 2024 - #include <iostream> #include <vector> #include <algorithm> class CustomComparator { int customParam; public: CustomComparator(int param) : customParam(param) {} bool operator()(int a, int b) const { // Use customParam in your comparison logic return (a % customParam) < (b % customParam); } }; int main() { std::vector<int> vec = {5, 3, 8, 1, 9}; int customParam = 3; CustomComparator comp(customParam); std::sort(vec.begin(), vec.end(), comp); for (int n : vec) { std::cout << n << ' '; } return 0; } Lambda functions can capture external variables, making it easier to pass extra parameters.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 8 )
October 20, 2025 - When we say that the ordering imposed by c on S is consistent with equals, we mean that the quotient for the ordering is the equivalence relation defined by the objects' equals(Object) method(s): ... Unlike Comparable, a comparator may optionally permit comparison of null arguments, while maintaining the requirements for an equivalence relation.
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › comparator-in-cpp
Custom Comparator in C++ - GeeksforGeeks
August 21, 2025 - It is used to sort a vector of integers based on the number of set bits using a lambda function as the custom comparator.
Find elsewhere
Top answer
1 of 1
3

I've unit-tested this with POD types, std::string, and std::unique_ptr<int> and it executes all functions without issue.

Nice to see you again! :)

As with your deque from last time, I think your coding style is very good but the actual design is a bit questionable. (Less so than last time, though.) Consider:

template<typename DataMember, typename lambdaEquals>
const type * const FindByKey(DataMember&& key, lambdaEquals& equals) const;  

eHeap<std::string, std::less<>> myHeap;
const std::string *it1 = myHeap.FindByKey("hello", std::equal<>);
const std::string *it2 = myHeap.FindByKey("world", std::equal<>);
const std::string *it3 = myHeap.FindByKey("foo", std::equal<>);

Notice that the type DataMember in the first two calls is const char (&)[6], because the thing we're perfect-forwarding is an lvalue of type const char[6]; and in the third call is const char (&)[4].

If I were designing the API, I'd provide simply

template<typename lambdaPredicate>
const type * const FindByKey(lambdaPredicate& equals) const;  

eHeap<std::string, std::less<>> myHeap;
const std::string *it1 = myHeap.FindByKey([](auto&& x){ return x == "hello"; });
const std::string *it2 = myHeap.FindByKey([](auto&& x){ return x == "world"; });
const std::string *it3 = myHeap.FindByKey([](auto&& x){ return x == "foo"; });

Now the caller doesn't have to worry about things like "is the DataMember the first or second argument to lambdaEquals?" or "does DataMember secretly have to bear some relationship to type?" or anything like that. The only parameter the caller needs to worry about is the predicate, which is an opaque lambda type that clearly can do whatever it wants.

Notice that the type lambdaPredicate is a different type in all three of the calls here. So we have a little bit more template explosion, maybe; but it'll all be inlined anyway.

Also, at this point, we've got something that's very close to the standard algorithm std::find_if. So we might like to get rid of the member-function algorithm and just provide a pair of member functions to create iterators into the unordered elements of the heap:

const type *unordered_begin() const { return heap; }
const type *unordered_end() const { return heap + heapSize; }

eHeap<std::string, std::less<>> myHeap;
const std::string *it1 = std::find_if(myHeap.unordered_begin(), myHeap.unordered_end(), [](auto&& x){ return x == "hello"; });

If we're providing const iterators, should we also provide non-const iterators?

type *unordered_begin() { return heap; }
type *unordered_end() { return heap + heapSize; }

Probably not. We don't want to give the user the ability to modify or reorder the heap's elements on the fly; that could break the heap invariant.


typedef eHeap<type, lambdaCompare> heap_t;

Did you know that you can use the name of the template itself as a class-name inside the definition of the template? That is, you could just use eHeap in all the places you're currently using heap_t, and the compiler would know that you're talking about eHeap<type, lambdaCompare>.

In any event, heap_t probably shouldn't be a public member typedef, should it?


const type * const      operator[](const int index) const;

Of the four consts on that line, two are redundant — even harmful. Prefer to write

const type *operator[](int index) const;

It doesn't matter for primitive types like int and type *, but if the parameter or the return value were class types, the added const would have made a difference:

X foo();
const X bar();

X x;
x = foo();  // move assignment
x = bar();  // copy assignment, since `const X` can't be moved-from — oops!

I prefer always to write the generic-safe version, even for primitive types, so that neither I nor the readers who come after me need to worry about whether this type is primitive or not — it's just obviously safe, and the reader doesn't need to expend mental effort on it.


int i;
// ...
for (i = 0; i < heapSize; i++)
    heap[i] = other.heap[i];

For the same reason, I write ++i even when i++ is just as fast for integers. (Well, in that case, it's also because the verb comes first in English. "Increment i" reads better than "i, increment".)

C++ isn't C89; you should never declare an uninitialized variable if you can possibly help it. Write:

for (int i = 0; i < heapSize; ++i)
    heap[i] = other.heap[i];

The line I // ...ed above was heap = new type[heapSize];. Why on earth are you using manual memory management in this class? Remember the Rule of Zero.

Use std::vector<type> heap; and get rid of the heapSize member variable (because you have heap.size() for that now). This not only protects you against memory leaks (e.g. consider what happens if one of those copy-assignments throws an exception) — it will also make your code more efficient, because the vector will track its own capacity separately from its length, and use geometric resizing to make sure that a sequence of O(n) calls to PushHeap results in only O(lg n) reallocations, instead of O(n) reallocations. It will also make your source code shorter, because you can get rid of those Allocate() and Resize() functions.

You can also get rid of all your special member functions (as the Rule of Zero suggests), which will shorten the code even more.


Finally, you might not be aware that even make_heap, push_heap and pop_heap are available as standard library functions!

The one heap-related function that I wish were available in the STL that currently isn't available is basically your ReplaceRoot, which pops the top element and then also pushes the provided element onto the heap in a single operation (which, as you noticed, can be done more efficiently than just a pop plus a push).


I have a "heap_span" on my GitHub that's similar to this code but doesn't even use a vector for storage; it just provides a view onto a sequence of elements allocated by the caller. It might or might not interest you. :)

🌐
USACO Guide
usaco.guide › home › general › (optional) c++ - lambda expressions
(Optional) C++ - Lambda Expressions · USACO Guide
The C++ standard library has good support for lambdas, with functions like std::sort and std::lower_bound allowing you to pass custom functions to act as a comparator of objects.
🌐
Coderanch
coderanch.com › t › 781949 › java › Comparator-lambda
Comparator with lambda (Features new in Java 8 forum at Coderanch)
So, we get: and so 5 is considered to be less than 4, and , and so 4 is considered to be bigger than 5. will do the necessary comparisons in the way described, and so the result is List(5, 4), because as said, 5 is less than 4 according to c.
🌐
Reddit
reddit.com › r/javahelp › lambda expression as a comparator?
r/javahelp on Reddit: lambda expression as a comparator?
September 23, 2023 -
  public static int longestStrChain(String[] words) {
    Arrays.sort(words, (a, b) -> a.length() - b.length());
    HashMap<String, Integer> dp = new HashMap<>();
    int max_chain = 0;
    for (String word : words) {
        dp.put(word, 1);
        for (int i = 0; i < word.length(); i++) {
            String prev_word = word.substring(0, i) + word.substring(i + 1);
            if (dp.containsKey(prev_word)) {
                dp.put(word, Math.max(dp.get(word), dp.get(prev_word) + 1));
            }
        }
        max_chain = Math.max(max_chain, dp.get(word));
    }
    return max_chain;
}

Can someone help me understand how doesArrays.sort(words, (a, b) -> a.length() - b.length()); actually work? they said that it's for sorting String array, descending order. I don't even know how this
does work i use the debugging tool and seems like it's looping through the array, i was fine with the for-each-loop sorting until this came in.

 for(int i = 0; i<words.length;i++) {
        for (int j = i; j < words.length; j++) {
            if (words[j].length()<words[i].length()){
                swap(j,i,words);

            }

could someone please explain this to me? the Array.sort is looping too so maybe it's the same?

Top answer
1 of 2
2
the Array.sort is looping too so maybe it's the same? Yes, the Arrays.sort(...) method is basically doing the same thing as the for loop you describe; except that instead of for loops, it will use a more efficient sorting algorithm, such as merge sort . The lambda is a shorthand way of writing a Comparator class. The comparator has a single compare method, which takes two parameters, and basically says how those two object should be ordered. The sorting algorithm uses the comparator to sort the array -- basically the same as the code in your if statement's condition.
2 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Reddit
reddit.com › r/learnjava › why does a lambda work as a comparator
r/learnjava on Reddit: Why does a lambda work as a comparator
September 13, 2023 -

rustic distinct meeting price sand sense rain many alleged instinctive

This post was mass deleted and anonymized with Redact

Top answer
1 of 7
6
Comparator (Java Platform SE 8 ) (oracle.com) Functional Interface: This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. I think generally in Java, if a interface has only one function, it can be a functional interface and used as a lambda.
2 of 7
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
StudyLib
studylib.net › doc › 28282019 › custom-comparator-in-c---stl
Custom Comparator in C++ STL (User-Defined Sorting Logic)
1 week ago - sort(v.begin(), v.end(), [](int a, int b) { return a &gt; b; }); For pairs: sort(v.begin(), v.end(), [](pair&lt;int,int&gt; a, pair&lt;int,int&gt; b) { return a.second &lt; b.second; }); Lambda is preferred in Competitive Programming because: * Short * No extra function * Easy to write Custom Comparator in priority_queue By default: * priority_queue = max heap To make min heap: priority_queue&lt;int, vector&lt;int&gt;, greater&lt;int&gt;&gt; pq; Or custom: struct cmp { bool operator()(int a, int b) { return a &gt; b; // min heap } }; priority_queue&lt;int, vector&lt;int&gt;, cmp&gt; pq; Rules of Comparator (VERY IMPORTANT) Your comparator must follow: Strict Weak Ordering That means: 1.
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › lambda-expression-in-c
Lambda Expression in C++ - GeeksforGeeks
A lambda function "[](const int& a, const int& b){ return a > b; }" is passed to sort() to compare elements and sort them in descending order. Finally, the sorted values are printed using a range-based for loop. CPP ·
Published   February 10, 2016
🌐
Vertex Academy
vertex-academy.com › tutorials › en › java-8-lambda-comparator-example
Java 8 Lambda: Comparator Example • Vertex Academy
January 26, 2018 - arraylist java example arraylist methods java check whether two strings are equal in java conditional operator java configuration create a variable in java development of html equals java equals java example for each loop in Java for each loop java history of java how java is used how to declare a constant in java how to raise a number to a power java how to raise a number to a power java without math.pow html history IDE Java java 8 lambda comparator java declare constant java editions java editions differences java history Java I/O java loops Java String charAt() Method java two dimensional
🌐
Educative
educative.io › answers › lambda-expressions-in-cpp
Lambda expressions in C++
In this example, we sort a vector descendingly. By default, the sort() function sorts ascendingly. However, we can pass a lambda expression as the third argument to the sort() function to have our own custom way of comparing vector elements.
🌐
Oreate AI
oreateai.com › blog › unlocking-custom-sorting-a-deep-dive-into-c-lambda-comparators › ab46585f8b0be719ea5ffba1a4f69865
Unlocking Custom Sorting: A Deep Dive Into C++ Lambda Comparators - Oreate AI Blog
January 27, 2026 - Explore how C++ lambda expressions provide an elegant and concise way to define custom sorting logic for algorithms like std::sort, enabling flexible ordering based on specific criteria.