Home  >  Article  >  Backend Development  >  How to implement custom sorting rules using C++ lambda expressions?

How to implement custom sorting rules using C++ lambda expressions?

王林
王林Original
2024-04-17 18:03:011095browse

Use C Lambda expressions to customize sorting rules to flexibly define sorting logic. The syntax is: [capture list](parameters) -> return type { body }. In the actual case, the lambda expression sortLambda sorts by string length, and the output is: dog, apple, banana, cherry, elephant.

用 C++ lambda 表达式自定义排序规则如何实现?

Use C Lambda expression to customize sorting rules

Lambda expression is an anonymous function that can be used in C to define custom sorting rules. It provides an easy and flexible way to sort your data based on custom logic.

Syntax

The typical lambda expression syntax is as follows:

[capture list](parameters) -> return type { body }

Among them:

  • capture list : Optional, used to capture references to external variables.
  • parameters: Optional, used to obtain input parameters.
  • -> return type: Optional, used to specify the return type.
  • body: Function body, containing the code to be executed.

Practical case

The following is a practical case using lambda expression to customize sorting rules, which is used to sort a string vector by its length:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    vector<string> strings = {"apple", "banana", "cherry", "dog", "elephant"};

    // 定义 lambda 表达式,将字符串按长度排序
    auto sortLambda = [](const string& a, const string& b) { return a.length() < b.length(); };

    // 使用 lambda 表达式对向量排序
    sort(strings.begin(), strings.end(), sortLambda);

    // 打印排序后的向量
    for (const string& s : strings) {
        cout << s << endl;
    }

    return 0;
}

Output

dog
apple
banana
cherry
elephant

In this example, the lambda expression sortLambda captures the external variables a and ## A reference to #b, and returns whether the length of a is less than the length of b. The sort function sort uses this lambda expression to sort a vector of strings in ascending order of their length.

The above is the detailed content of How to implement custom sorting rules using C++ lambda expressions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn