跳到内容

函数对象与算法 ​

STL 算法(#include <algorithm>)接受一对迭代器划定范围,再接受一个"可调用对象"决定具体行为。可调用对象不止是普通函数——重载了 operator() 的类对象(函数对象,也叫 functor)也能用。函数对象的优势是能携带状态:构造时保存参数,调用时使用它。配合 <functional> 里的预定义函数对象和适配器,可以写出非常紧凑的算法调用。

函数对象:重载 operator() ​

任何重载了 operator() 的类,其实例都可以像函数一样"调用":

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

// 一个带状态的判断器:判断值是否超过阈值
class OverLimit {
public:
    explicit OverLimit(int lim) : lim_(lim) {}
    bool operator()(int v) const { return v > lim_; }
private:
    int lim_;
};

int main()
{
    std::vector<int> data{12, 55, 8, 130, 42, 200};

    // 用函数对象作为 count_if 的谓词
    int n = std::count_if(data.begin(), data.end(), OverLimit(50));
    std::cout << "超过 50 的个数 = " << n << "\n";

    // 临时构造不同阈值的函数对象
    int m = std::count_if(data.begin(), data.end(), OverLimit(100));
    std::cout << "超过 100 的个数 = " << m << "\n";
    return 0;
}

OverLimit(50) 构造一个匿名对象,它的 lim_ 是 50;count_if 对每个元素调用它的 operator()。同一个类换个构造参数就是新判断器,这是函数对象比普通函数灵活的地方。

预定义函数对象 ​

<functional> 提供了一批现成的函数对象模板,省得自己写:

cpp
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>

int main()
{
    std::vector<int> a{1, 2, 3, 4};
    std::vector<int> b{10, 20, 30, 40};
    std::vector<int> sum(a.size());

    // plus<int>():两个数相加
    std::transform(a.begin(), a.end(), b.begin(), sum.begin(),
                   std::plus<int>());
    for (int x : sum) std::cout << x << " ";   // 11 22 33 44
    std::cout << "\n";

    // greater<int>():大于比较,配合 sort 降序排列
    std::vector<int> v{5, 1, 4, 2, 3};
    std::sort(v.begin(), v.end(), std::greater<int>());
    for (int x : v) std::cout << x << " ";     // 5 4 3 2 1
    std::cout << "\n";
    return 0;
}

常用预定义函数对象:plus、minus、multiplies、divides、modulus(算术),negate(取负),equal_to、not_equal_to、greater、less、greater_equal、less_equal(比较),logical_and、logical_or、logical_not(逻辑)。它们都是模板,要指定元素类型。

函数适配器与 std::bind ​

有时候现成函数对象的参数顺序或个数对不上。老式 bind1st / bind2nd 已被弃用,C++11 起用更通用的 std::bind(#include <functional>),可以固定某些参数:

cpp
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> v{5, 12, 8, 25, 3, 30};

    // 用 bind 把 greater 的第一个参数固定为 10
    // greater(10, x) 即 "10 > x",也就是 "x < 10"
    auto lessThan10 = std::bind(std::greater<int>(), 10, std::placeholders::_1);
    int n = std::count_if(v.begin(), v.end(), lessThan10);
    std::cout << "小于 10 的个数 = " << n << "\n";

    // 直接把 lambda 当谓词,更直观(下节会讲)
    int m = std::count_if(v.begin(), v.end(),
                          [](int x){ return x < 10; });
    std::cout << "(lambda 版)小于 10 的个数 = " << m << "\n";
    return 0;
}

std::placeholders::_1 是占位符,表示"调用时传入的第一个参数"。bind 把 greater<int>()、固定值 10、占位符 _1 组合成一个新的可调用对象。现代 C++ 里,简单场景更推荐 lambda(下一章详讲),bind 主要留给需要保存复杂可调用对象的场合。

常用算法速览 ​

STL 算法分几大类,记住每组代表即可:

cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>        // accumulate, iota

void show(const std::vector<int>& v) {
    for (int x : v) std::cout << x << " ";
    std::cout << "\n";
}

int main()
{
    std::vector<int> v{5, 3, 8, 1, 9, 2};

    // 遍历
    std::for_each(v.begin(), v.end(),
                  [](int x){ std::cout << x << ","; });
    std::cout << "\n";

    // 查找
    auto it = std::find(v.begin(), v.end(), 8);
    std::cout << "find 8: " << (it != v.end()) << "\n";
    std::cout << "find_if >7: " << *std::find_if(v.begin(), v.end(),
                  [](int x){ return x > 7; }) << "\n";

    // 计数
    std::cout << "count 偶数 = "
              << std::count_if(v.begin(), v.end(),
                  [](int x){ return x % 2 == 0; }) << "\n";

    // 排序(升序,默认)
    std::sort(v.begin(), v.end());
    show(v);

    // 累加
    std::cout << "sum = " << std::accumulate(v.begin(), v.end(), 0) << "\n";

    // 生成(用 lambda 填充)
    std::vector<int> g(5);
    std::generate(g.begin(), g.end(), [n = 0]() mutable { return n += 2; });
    show(g);     // 2 4 6 8 10

    // transform:逐元素变换后写入另一区间
    std::vector<int> doubled(v.size());
    std::transform(v.begin(), v.end(), doubled.begin(),
                   [](int x){ return x * 2; });
    show(doubled);

    // remove_if + erase:真正删除满足条件的元素
    v.erase(std::remove_if(v.begin(), v.end(),
                           [](int x){ return x < 5; }), v.end());
    show(v);
    return 0;
}

注意最后那个擦除-移除惯用法:std::remove_if 本身不删元素(它没法改容器大小),只是把要保留的元素前移,返回新的逻辑尾迭代器;再用容器的 erase 把尾巴真正删掉。这是 STL 经典套路,C++20 起可直接用 std::erase_if(v, pred) 简化。

函数对象 vs 函数指针 vs lambda ​

三种可调用对象都能传给算法:

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

bool isEven(int x) { return x % 2 == 0; }      // 普通函数
struct IsEven {                                  // 函数对象
    bool operator()(int x) const { return x % 2 == 0; }
};

int main()
{
    std::vector<int> v{1, 2, 3, 4, 5, 6};

    // 函数指针
    std::cout << std::count_if(v.begin(), v.end(), isEven) << "\n";
    // 函数对象
    std::cout << std::count_if(v.begin(), v.end(), IsEven{}) << "\n";
    // lambda
    std::cout << std::count_if(v.begin(), v.end(),
                               [](int x){ return x % 2 == 0; }) << "\n";
    return 0;
}

函数指针最简单但无法携带状态;函数对象能带状态但要多写一个类;lambda 兼顾简洁与状态,现代代码里首选。函数指针和函数对象在某些场合仍不可替代(如配合老接口、需要在多处复用同一逻辑),理解它们能看懂既有代码。

课后练习 ​

  1. 自定义函数对象:写一个 class IsMultipleOf,构造时接收一个整数 m,operator() 判断传入值是否为 m 的倍数。用它配合 std::count_if 统计一个 vector<int> 里 3 的倍数和 7 的倍数各有多少。
  2. 预定义函数对象:用 std::multiplies<int> 配合 std::transform,把两个等长 vector<int> 对应元素相乘,结果存入第三个 vector。再用 std::greater<int> 配合 std::sort 对一个 vector 降序排序。
  3. 擦除-移除惯用法:给定一个含正负数的 vector<int>,用 std::remove_if + erase 删除所有负数,遍历打印结果。理解为什么光调 remove_if 不够。
  4. transform 自定义变换:用 std::transform 把一个 std::vector<std::string> 里的每个字符串转换为其长度(std::string::size()),结果存入 std::vector<std::size_t>。提示:写一个返回长度的可调用对象(函数或 lambda)。