当前位置: 首页 > article >正文

C++中std::count` 和 `std::count_if`的用法和示例

在 C++ 标准库中,std::countstd::count_if 是两个用于统计容器中满足特定条件的元素数量的算法。它们的核心区别在于判断条件的形式,以下是详细用法和示例:


1. std::count

作用:统计区间内 等于指定值 的元素数量。
适用场景:直接比较元素是否等于某个固定值。
函数原型

template< class InputIt, class T >
typename iterator_traits<InputIt>::difference_type
    count( InputIt first, InputIt last, const T& value );
示例代码
#include <iostream>
#include <vector>
#include <algorithm> // 必须包含此头文件

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

    // 统计值为 2 的元素数量
    int cnt = std::count(nums.begin(), nums.end(), 2);
    std::cout << "Number of 2s: " << cnt << std::endl; // 输出 3

    return 0;
}

2. std::count_if

作用:统计区间内 满足谓词条件 的元素数量。
适用场景:需要自定义判断逻辑(如范围比较、字符串长度等)。
函数原型

template< class InputIt, class UnaryPredicate >
typename iterator_traits<InputIt>::difference_type
    count_if( InputIt first, InputIt last, UnaryPredicate p );
示例代码
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

int main() {
    std::vector<int> nums = {10, 25, 30, 15, 5};
    std::vector<std::string> words = {"apple", "banana", "cherry", "date"};

    // 统计大于 20 的元素数量
    int cnt1 = std::count_if(nums.begin(), nums.end(), [](int x) {
        return x > 20;
    });
    std::cout << "Elements > 20: " << cnt1 << std::endl; // 输出 2

    // 统计长度超过 5 的字符串数量
    int cnt2 = std::count_if(words.begin(), words.end(), [](const std::string& s) {
        return s.size() > 5;
    });
    std::cout << "Words longer than 5: " << cnt2 << std::endl; // 输出 2

    return 0;
}

核心区别

特性std::countstd::count_if
判断条件直接比较元素是否等于 value通过谓词(函数、Lambda)自定义条件
灵活性低(仅支持相等性检查)高(支持任意复杂条件)
典型用途统计特定值的出现次数统计满足范围、模式或复合条件的元素

高级用法示例

1. 使用函数对象(Functor)
struct IsEven {
    bool operator()(int x) const { return x % 2 == 0; }
};

int main() {
    std::vector<int> nums = {1, 2, 3, 4, 5};
    int cnt = std::count_if(nums.begin(), nums.end(), IsEven());
    std::cout << "Even numbers: " << cnt << std::endl; // 输出 2
    return 0;
}
2. 结合标准库预定义谓词
#include <functional> // 包含 std::greater, std::less 等

int main() {
    std::vector<int> nums = {10, 20, 30, 40};
    // 统计大于 25 的元素数量
    int cnt = std::count_if(nums.begin(), nums.end(), 
        std::bind(std::greater<int>(), std::placeholders::_1, 25));
    std::cout << "Elements > 25: " << cnt << std::endl; // 输出 2
    return 0;
}

性能与注意事项

  • 时间复杂度:均为 O(n),需遍历整个区间。
  • 谓词设计:确保谓词无副作用且高效,避免修改元素或容器。
  • 迭代器有效性:区间 [first, last) 必须有效。

总结

  • std::count:简单统计特定值的数量。
  • std::count_if:灵活统计满足自定义条件的元素数量,支持 Lambda、函数对象或标准谓词。
    两者结合使用,可高效处理各类统计需求,是数据分析、过滤和条件检查的常用工具。

http://www.kler.cn/a/586991.html

相关文章:

  • 数据结构-单链表专题
  • 【开源代码解读】AI检索系统R1-Searcher通过强化学习RL激励大模型LLM的搜索能力
  • DataEase:一款国产开源数据可视化分析工具
  • 蓝桥杯Python赛道备赛——Day5:算术(一)(数学问题)
  • 在Linux中安装Nginx
  • 机器学习之线性代数
  • 【蓝桥杯】24省赛:数字串个数
  • 使用 BookMarkHub 插件进行书签同步
  • 一文了解CAS
  • linux 命令 ls
  • 网络爬虫【简介】
  • 基于vue-grid-layout 实现自定义首页视图
  • Tailwindcss开启黑夜模式
  • Python扑克牌游戏更新哦~【增加更多牌类】
  • 获取golang变量的类型
  • Redis分片集群
  • 机器学习与深度学习中模型训练时常用的四种正则化技术L1,L2,L21,ElasticNet
  • springboot集成flink实现DM数据库同步到ES
  • RabbitMq C++客户端的使用
  • 使用SetupTools 管理你的项目打包工作