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

   2024-10-01 5280
核心提示:要编写自定义比较函数来使用 stable_sort 函数进行稳定排序,我们需要定义一个函数,该函数接受两个参数并返回一个布尔值,用于

要编写自定义比较函数来使用 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 向量进行稳定排序。排序后,我们打印出排序前后的结果,以验证排序是否正确。

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

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号