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;
}

代码解析:

  1. 定义函数类型 Func 为 function<void()>,表示无参数无返回值的函数类型。
  2. isFuncExist 函数接受一个 vector<Func> 和一个 Func 作为参数,使用 std::find_if 算法查找 vector 中与传入 Func 类型相同的函数。
  3. find_if 算法使用一个 lambda 表达式作为谓词,用于比较函数的类型。
  4. 如果找到匹配的函数,find_if 返回指向该函数的迭代器,否则返回 funcs.end()。
  5. isFuncExist 函数返回 find_if 返回的迭代器是否等于 funcs.end(),从而判断函数是否已经存在于 vector 中。

注意:

  • 以上代码仅判断函数类型是否相同,如果需要判断函数的具体实现,需要使用其他方法。
  • 实际应用中,可以使用 std::unordered_set 或 std::map 来存储函数,以便更快速地判断函数是否存在。

希望本文对您有所帮助!

C++ 使用 std::find_if 判断函数是否存在于 vector 中