函数指针用于 stl 算法,通过其地址引用函数,用于传递自定义行为。使用时需声明一个指向函数类型的指针,并向 stl 算法传递以自定义排序或操作方式。一个实战案例是按字母顺序对字符串列表进行排序,通过定义一个比较函数,并将其传递给 std::sort 函数实现。

C++ 函数指针如何用于 STL 算法
函数指针提供了一种通过其地址引用函数的方式。在 C++ 中,它们用于向 STL 算法传递自定义行为。
使用函数指针
立即学习“C++免费学习笔记(深入)”;
要使用函数指针,需要声明一个指向函数类型的指针:
int (*cmp)(int, int);
此指针指向返回 int 值并接受两个 int 类型的参数的函数。
向 STL 算法传递函数指针
可以向 std::sort 等 STL 算法传递函数指针,以自定义排序方式。例如,以下代码按降序对向量排序:
// 定义比较函数
int cmp(int a, int b) {
return a > b;
}
int main() {
std::vector<int> v = {1, 3, 2, 4};
std::sort(v.begin(), v.end(), cmp);
// 输出排序后的向量
for (auto& x : v) {
std::cout << x << " ";
}
}实战案例
考虑一个需要根据字母顺序对字符串列表进行排序的程序。以下是使用函数指针的解决方案:
#include <algorithm>
#include <vector>
#include <string>
int main() {
std::vector<std::string> words = {"apple", "banana", "cherry", "dog"};
// 定义比较函数
int cmp(const std::string& a, const std::string& b) {
return a < b;
}
std::sort(words.begin(), words.end(), cmp);
for (auto& word : words) {
std::cout << word << " ";
}
return 0;
}以上就是C++ 函数指针如何用于STL算法?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号