【c++STL算数仿函数,关系仿函数,逻辑仿函数】

C++ STL中的算数、关系和逻辑仿函数

STL(Standard Template Library)是C++标准库的一部分,提供了许多强大的工具和功能,其中包括仿函数(function object)。仿函数是一种类或结构体,类似函数指针,可被用于执行函数调用。在STL中,有三种重要的仿函数类型:算数、关系和逻辑仿函数。

1. 算数仿函数

算数仿函数用于执行基本的数学运算,如加法、减法、乘法和除法。STL提供了几个算数仿函数,包括 plusminusmultipliesdivides

实战示例:

#include <iostream>
#include <functional>

int main() {
    std::plus<int> add;
    std::minus<int> subtract;
    std::multiplies<int> multiply;
    std::divides<int> divide;

    int a = 10, b = 5;

    // 使用算数仿函数执行运算
    std::cout << "Addition: " << add(a, b) << std::endl;
    std::cout << "Subtraction: " << subtract(a, b) << std::endl;
    std::cout << "Multiplication: " << multiply(a, b) << std::endl;
    std::cout << "Division: " << divide(a, b) << std::endl;

    return 0;
}

2. 关系仿函数

关系仿函数用于比较两个值的关系,返回布尔值,如 greaterlessequal_to 等。这些仿函数可以用于容器的排序和查找算法。

实战示例:

#include <iostream>
#include <functional>

int main() {
    std::greater<int> greater_than;
    std::less<int> less_than;
    std::equal_to<int> equal;

    int x = 10, y = 5;

    // 使用关系仿函数比较值的关系
    std::cout << "x > y: " << greater_than(x, y) << std::endl;
    std::cout << "x < y: " << less_than(x, y) << std::endl;
    std::cout << "x == y: " << equal(x, y) << std::endl;

    return 0;
}

3. 逻辑仿函数

逻辑仿函数执行逻辑运算,比如逻辑与、逻辑或和逻辑非。STL中提供了 logical_andlogical_orlogical_not 等仿函数。

实战示例:

#include <iostream>
#include <functional>

int main() {
    std::logical_and<bool> logic_and;
    std::logical_or<bool> logic_or;
    std::logical_not<bool> logic_not;

    bool p = true, q = false;

    // 使用逻辑仿函数执行逻辑运算
    std::cout << "p && q: " << logic_and(p, q) << std::endl;
    std::cout << "p || q: " << logic_or(p, q) << std::endl;
    std::cout << "!p: " << logic_not(p) << std::endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

武帝为此

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值