C++ std::sort 函数
在 C++ 里,std::sort
函数的第三个参数是一个比较函数或者可调用对象,用于定义元素的排序规则。以下为你详细介绍几种常见的传入形式:
1. 普通函数
普通函数可以当作比较函数传入 std::sort
。此函数要接收两个同类型的参数,并且返回一个布尔值,用于表明第一个参数是否应该排在第二个参数之前。
#include <iostream>
#include <vector>
#include <algorithm>// 普通比较函数
bool compare(int a, int b) {return a < b;
}int main() {std::vector<int> numbers = {5, 2, 8, 1, 9};std::sort(numbers.begin(), numbers.end(), compare);for (int num : numbers) {std::cout << num << " ";}std::cout << std::endl;return 0;
}
2. Lambda 表达式
Lambda 表达式是一种匿名函数,能方便地在 std::sort
中定义比较规则。
#include <iostream>
#include <vector>
#include <algorithm>int main() {std::vector<int> numbers = {5, 2, 8, 1, 9};std::sort(numbers.begin(), numbers.end(), [](int a, int b) {return a < b;});for (int num : numbers) {std::cout << num << " ";}std::cout << std::endl;return 0;
}
3. 函数对象(Functor)
函数对象是实现了 operator()
的类或者结构体实例。借助函数对象,能够在比较过程中保存状态。
#include <iostream>
#include <vector>
#include <algorithm>// 函数对象 升序 (a>b为降序)
struct Compare {bool operator()(int a, int b) const {return a < b;}
};int main() {std::vector<int> numbers = {5, 2, 8, 1, 9};// Compare comp;// std::sort(numbers.begin(), numbers.end(), comp);std::sort(numbers.begin(), numbers.end(), Compare());for (int num : numbers) {std::cout << num << " ";}std::cout << std::endl;return 0;
}
4. 类的静态成员函数
类的静态成员函数不依赖于类的实例,没有 this
指针,能够直接作为比较函数传入 std::sort
。
#include <iostream>
#include <vector>
#include <algorithm>class MyClass {
public:static bool compare(int a, int b) {return a < b;}
};int main() {std::vector<int> numbers = {5, 2, 8, 1, 9};std::sort(numbers.begin(), numbers.end(), MyClass::compare);for (int num : numbers) {std::cout << num << " ";}std::cout << std::endl;return 0;
}
注意事项
- 比较函数或者可调用对象必须满足严格弱序的要求,即对于任意元素
a
、b
和c
,需要满足以下条件:compare(a, a)
始终为false
。- 若
compare(a, b)
为true
,则compare(b, a)
为false
。 - 若
compare(a, b)
为true
且compare(b, c)
为true
,则compare(a, c)
为true
。 - 若
!compare(a, b)
且!compare(b, a)
,则对于任意c
,compare(a, c)
和compare(b, c)
具有相同的结果。
这些规则保证了排序的正确性和稳定性。