【C++】简化for-range的算法函数

本文介绍了C++中几个标准库算法,如std::any_of、std::all_of、std::count_if和std::transform,以及如何使用lambda表达式简化对容器元素的操作,包括检查条件、计数和转换。
摘要由CSDN通过智能技术生成

简化对容器中元素的循环操作:

std::any_of用于检查是否有任何元素满足给定条件

std::all_of用于检查容器中的所有元素是否都满足条件

std::count_if用于统计满足条件的元素个数

std::transform用于对一个序列中的每个元素进行转换,并将结果存储到另一个序列中

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

bool CHECK_DATA(int value) {
    // 这里可以根据实际情况编写条件判断的函数
    return value % 2 == 0;
}

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

    // 使用 std::any_of
    if (std::any_of(result.begin(), result.end(), CHECK_DATA)) {
        std::cout << "At least one element satisfies the condition." << std::endl;
    } else {
        std::cout << "No elements satisfy the condition." << std::endl;
    }

    // 使用 std::all_of
    if (std::all_of(result.begin(), result.end(), CHECK_DATA)) {
        std::cout << "All elements satisfy the condition." << std::endl;
    } else {
        std::cout << "Not all elements satisfy the condition." << std::endl;
    }

    int nums = std::count_if(result.begin(), result.end(),
                             [](const auto& res) { return CHECK_DATA(res); });
    std::cout << "NUMS = " << nums << std::endl;
    return 0;
}
At least one element satisfies the condition.
Not all elements satisfy the condition.      
NUMS = 2  
std::unordered_map<std::string, ComplexMat> mat_set;
std::vector<ComplexMat> res;
res.reserve(mat_set.size());
std::transform(mat_set.begin(), mat_set.end(), std::back_inserter(res),
                 [](const auto& pair) { return pair.second; });

这段代码使用了lambda表达式作为std::transform函数的第四个参数,用于将mat_set中的所有ComplexMat对象存储到res向量中。

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

void myFunction(int n) {
    std::cout << n << " ";
}

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

    // 对容器中的每个元素应用指定的函数
    std::for_each(numbers.begin(), numbers.end(), [](int n) {
        std::cout << n * 2 << " ";
    });

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

拾牙慧者

欢迎请作者喝奶茶

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

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

打赏作者

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

抵扣说明:

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

余额充值