C++高级教程
+ -

C++ 仿函数(Functors)

2023-07-12 10 0

在C++中,仿函数(Functors)是一种重载了函数调用运算符 operator() 的类或结构体。它可以像函数一样被调用,有助于实现更灵活和可定制的函数对象。

下面是C++中仿函数的各种用法和示例代码:

1. 作为函数对象调用:

#include <iostream>

struct Multiply {
    int operator()(int a, int b) const {
       return a * b;
    }
};

int main() {
    Multiply multiply;
    int result = multiply(5, 3); // 通过调用函数对象实现乘法运算
    std::cout << "Result: " << result << std::endl;
    return 0;
}

2. 作为算法的参数传递:

#include <iostream>
#include <vector>
#include <algorithm>

struct GreaterThan {
    int threshold;
    GreaterThan(int threshold) : threshold(threshold) {}

    bool operator()(int num) const {
        return num > threshold;
    }
};

int main() {
    std::vector<int> nums {1, 2, 3, 4, 5};
    int threshold = 3;

    // 通过仿函数作为比较条件,筛选大于阈值的元素
    auto it = std::find_if(nums.begin(), nums.end(), GreaterThan(threshold));

    if (it != nums.end()) {
        std::cout << "Found element greater than " << threshold << ": " << *it << std::endl;
    } else {
        std::cout << "No element found." << std::endl;
    }

    return 0;
}

3. 作为排序的比较函数:

#include <iostream>
#include <vector>
#include <algorithm>

struct SortByLength {
    bool operator()(const std::string& str1, const std::string& str2) const {
        return str1.length() < str2.length();
    }
};

int main() {
    std::vector<std::string> words {"apple", "banana", "orange", "grape", "pear"};

    // 使用仿函数改变字符串按长度进行排序
    std::sort(words.begin(), words.end(), SortByLength());

    for (const auto& word : words) {
        std::cout << word << std::endl;
    }

    return 0;
}

仿函数提供了一种灵活的方式来定义函数行为,并可以直接调用函数对象或者将其作为参数传递给算法和函数模板,从而实现更加灵活和可定制的编程。它在STL中被广泛应用,能够方便地定制算法的行为和操作。

0 篇笔记 写笔记

C++11 Lambda与仿函数
在C++11之彰,我们在使用 STL算法时,通常会用一些特别的对象-仿函数。其本质就是重定义了成员函数operator的一种自定义类型对象。这样的函数有个特点,就是使用在代码层和普通的函数并无两样,但其本质并非相同。一般情况下,仿函数我们可以写作如下:class CFactor{public:......
C++ 仿函数(Functors)
在C++中,仿函数(Functors)是一种重载了函数调用运算符 operator() 的类或结构体。它可以像函数一样被调用,有助于实现更灵活和可定制的函数对象。下面是C++中仿函数的各种用法和示例代码:1. 作为函数对象调用:#include struct ......
作者信息
我爱内核
Windows驱动开发,网站开发
好好学习,天天向上。
取消
感谢您的支持,我会继续努力的!
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

您的支持,是我们前进的动力!