21xrx.com
2024-09-20 05:27:38 Friday
登录
文章检索 我的文章 写文章
C++仿函数排序技巧
2023-07-11 20:20:46 深夜i     --     --
C++ 仿函数 排序技巧 STL Lambda表达式

C++中的仿函数是一种重载了函数调用操作符的类对象,被广泛用于排序、查找和算法等操作中。使用仿函数可以方便地对容器中的元素进行排序。下面介绍一些C++仿函数排序技巧。

1. 使用标准库中的`sort()`函数

C++标准库中提供了`sort()`函数,可以直接对容器进行排序。`sort()`函数接受三个参数:容器的起始和终止迭代器以及一个可选的仿函数对象。如果不提供仿函数,则默认使用`less<>`。


#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

int main()

{

  vector<int> nums5;

  // 使用默认的仿函数对象less<>进行排序

  sort(nums.begin(), nums.end());

  for (auto num : nums)

    cout << num << " ";

  

  return 0;

}

输出结果为:1 2 3 4 5。

2. 自定义仿函数对象

如果需要按照自己的需求进行排序,则可以自定义仿函数对象。假设要按照字符串长度进行排序,则可以实现以下仿函数对象:


#include <string>

class CompareStringLength {

public:

  bool operator()(const std::string& str1, const std::string& str2) const

  {

    return str1.length() < str2.length();

  }

};

在`sort()`函数中使用自定义的仿函数对象进行排序:


#include <iostream>

#include <vector>

#include <algorithm>

#include <string>

using namespace std;

class CompareStringLength {

public:

  bool operator()(const std::string& str1, const std::string& str2) const

  {

    return str1.length() < str2.length();

  }

};

int main()

{

  vector<string> strs "morning";

  // 使用自定义的仿函数对象进行排序

  sort(strs.begin(), strs.end(), CompareStringLength());

  for (auto str : strs)

    cout << str << " ";

  

  return 0;

}

输出结果为:good hello world morning。

3. 使用Lambda表达式

Lambda表达式是一种“匿名函数”,可用于创建短小的函数对象。使用Lambda表达式可以更方便地实现自定义的排序方法。


#include <iostream>

#include <vector>

#include <algorithm>

#include <string>

using namespace std;

int main()

{

  vector<string> strs"hello";

  // 使用Lambda表达式进行排序

  sort(strs.begin(), strs.end(), [](const std::string& str1, const std::string& str2) {

    return str1.length() < str2.length();

  });

  for (auto str : strs)

    cout << str << " ";

  

  return 0;

}

输出结果为:good hello world morning。

总之,仿函数在C++中广泛应用于排序、查找和算法等操作中,使用相应的技巧可以方便地实现自定义的排序方法。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复