[C++] 基础教程 - std::count函数介绍和使用场景

std::count函数

1. 函数介绍

std::count是C++标准库中的一个算法,用于计算给定值在指定范围内出现的次数。它的原型如下:

template <class InputIt, class T>
size_t count(InputIt first, InputIt last, const T& value);

其中,firstlast表示范围的起始和结束迭代器,value表示要查找的值。函数返回一个size_t类型的值,表示value在指定范围内出现的次数。

2. 使用场景

std::count函数在以下场景中非常有用:

2.1 统计数组中某个元素的出现次数

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

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

    size_t count = std::count(nums.begin(), nums.end(), target);
    std::cout << "The number " << target << " appears " << count << " times in the array." << std::endl;

    return 0;
}

输出结果:

The number 2 appears 3 times in the array.

2.2 统计字符串中某个字符的出现次数

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string str = "hello world";
    char target = 'l';

    size_t count = std::count(str.begin(), str.end(), target);
    std::cout << "The character '" << target << "' appears " << count << " times in the string." << std::endl;

    return 0;
}

输出结果:

The character 'l' appears 3 times in the string.

2.3 统计容器中某个元素的出现次数

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

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

    size_t count = std::count(nums.begin(), nums.end(), target);
    std::cout << "The number " << target << " appears " << count << " times in the vector." << std::endl;

    std::set<int> s = {1, 2, 3, 4, 5, 2, 3, 2};
    count = std::count(s.begin(), s.end(), target);
    std::cout << "The number " << target << " appears " << count << " times in the set." << std::endl;

    return 0;
}

输出结果:

The number 2 appears 3 times in the vector.
The number 2 appears 3 times in the set.

3. 总结

std::count函数是一个非常实用的算法,它可以帮助我们快速统计给定值在指定范围内的出现次数。无论是统计数组、字符串还是容器中的元素出现次数,都可以使用std::count函数轻松实现。

  • 12
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

老狼IT工作室

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

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

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

打赏作者

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

抵扣说明:

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

余额充值