C++ 使用 std::find_if 判断函数是否存在于 vector 中
C++ 使用 std::find_if 判断函数是否存在于 vector 中
在 C++ 中,我们可以使用 std::find_if 算法来判断一个函数是否已经存在于 vector 中。
示例代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
// 定义函数类型
typedef function<void()> Func;
// 判断函数是否已经存在vector中的函数
bool isFuncExist(vector<Func>& funcs, Func func) {
auto iter = find_if(funcs.begin(), funcs.end(), [func](const Func& f) {
return f.target_type() == func.target_type();
});
return iter != funcs.end();
}
int main() {
// 定义函数
auto func1 = []() { cout << 'Func1' << endl; };
auto func2 = []() { cout << 'Func2' << endl; };
auto func3 = []() { cout << 'Func3' << endl; };
// 定义vector并添加函数
vector<Func> funcs;
funcs.push_back(func1);
funcs.push_back(func2);
// 判断函数是否已经存在vector中
cout << isFuncExist(funcs, func1) << endl; // 输出1,即存在
cout << isFuncExist(funcs, func3) << endl; // 输出0,即不存在
return 0;
}
代码解析:
- 定义函数类型
Func为function<void()>,表示无参数无返回值的函数类型。 isFuncExist函数接受一个vector<Func>和一个Func作为参数,使用std::find_if算法查找vector中与传入Func类型相同的函数。find_if算法使用一个 lambda 表达式作为谓词,用于比较函数的类型。- 如果找到匹配的函数,
find_if返回指向该函数的迭代器,否则返回funcs.end()。 isFuncExist函数返回find_if返回的迭代器是否等于funcs.end(),从而判断函数是否已经存在于vector中。
注意:
- 以上代码仅判断函数类型是否相同,如果需要判断函数的具体实现,需要使用其他方法。
- 实际应用中,可以使用
std::unordered_set或std::map来存储函数,以便更快速地判断函数是否存在。
希望本文对您有所帮助!
AI 优化版
原文地址:https://www.cveoy.top/t/topic/olRb 著作权归作者所有。请勿转载和采集!