c++

C++ stable_sort的自定义比较函数如何编写

小樊
84
2024-08-19 22:03:33
栏目: 编程语言

要编写自定义比较函数来使用 stable_sort 函数进行稳定排序,我们需要定义一个函数,该函数接受两个参数并返回一个布尔值,用于指示哪个元素应排在前面。

以下是一个示例代码,演示如何编写一个自定义比较函数来对字符串长度进行稳定排序:

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

// 自定义比较函数,按字符串长度进行排序
bool compareLength(const std::string& str1, const std::string& str2) {
    return str1.length() < str2.length();
}

int main() {
    std::vector<std::string> strings = {"apple", "banana", "orange", "kiwi", "pear"};

    std::cout << "Before sorting:" << std::endl;
    for (const auto& str : strings) {
        std::cout << str << " ";
    }
    std::cout << std::endl;

    // 使用自定义比较函数进行稳定排序
    std::stable_sort(strings.begin(), strings.end(), compareLength);

    std::cout << "After sorting by length:" << std::endl;
    for (const auto& str : strings) {
        std::cout << str << " ";
    }
    std::cout << std::endl;

    return 0;
}

在上面的示例中,我们定义了一个名为 compareLength 的自定义比较函数,该函数接受两个参数,即两个字符串的引用,然后比较它们的长度并返回比较结果。在 main 函数中,我们使用 stable_sort 函数并传入自定义比较函数,对 strings 向量进行稳定排序。排序后,我们打印出排序前后的结果,以验证排序是否正确。

通过编写类似上面的代码,您可以自定义比较函数来对各种类型的数据进行稳定排序。

0
看了该问题的人还看了