C语言中如何实现类似STL的count功能?

99ANYc3cd6
预计阅读时长 17 分钟
位置: 首页 C语言 正文

std::count 是 C++ 标准库的一部分,而不是 C 语言,C 语言没有标准模板库,因此也没有 std::count

c语言stlcount
(图片来源网络,侵删)

std::count 是定义在 C++<algorithm> 头文件中的一个非常有用的算法,用于计算在一个范围(range)内某个特定值出现的次数。


std::count 的基本概念

std::count 通过迭代器来定义它要搜索的范围,这意味着它可以用于任何提供了迭代器的标准容器,std::vector, std::list, std::string, std::array 等,甚至可以用于普通的 C 风格数组。

函数原型

std::count 有两个主要版本:

用于比较值

template< class InputIt, class T >
typename std::iterator_traits<InputIt>::difference_type
    count( InputIt first, InputIt last, const T& value );
  • InputIt first: 指向搜索范围起始位置的迭代器。
  • InputIt last: 指向搜索范围结束位置的迭代器(注意:这个位置本身不参与搜索)。
  • const T& value: 你要查找的目标值。
  • 返回值: 目标值在范围内出现的次数,返回类型是 InputIt 的差值类型(对于大多数容器是 size_tptrdiff_t)。

用于使用自定义谓词

template< class InputIt, class UnaryPredicate >
typename std::iterator_traits<InputIt>::difference_type
    count_if( InputIt first, InputIt last, UnaryPredicate p );
  • 这个版本不查找特定值,而是统计满足某个条件的元素数量。p 是一个一元谓词(一个返回 bool 的函数或函数对象),如果元素满足条件,则返回 true

使用示例

示例 1:在 std::vector 中使用

这是最常见的用法。

c语言stlcount
(图片来源网络,侵删)
#include <iostream>
#include <vector>
#include <algorithm> // 必须包含 <algorithm> 头文件
int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 2, 2, 5, 6, 2};
    // 统计数字 2 出现的次数
    int count_of_2 = std::count(numbers.begin(), numbers.end(), 2);
    std::cout << "The number 2 appears " << count_of_2 << " times." << std::endl;
    // 统计数字 7 出现的次数(它不存在)
    int count_of_7 = std::count(numbers.begin(), numbers.end(), 7);
    std::cout << "The number 7 appears " << count_of_7 << " times." << std::endl;
    return 0;
}

输出:

The number 2 appears 4 times.
The number 7 appears 0 times.

示例 2:在 C 风格数组上使用

std::count 也可以用于 C 风格数组,只要我们提供指向数组开头和结尾下一个位置的指针。

#include <iostream>
#include <algorithm>
int main() {
    char sentence[] = "Hello, World! Hello, C++!";
    char to_find = 'l';
    // sentence 指向数组开头
    // sentence + sizeof(sentence) - 1 指向字符串的最后一个字符
    // 我们需要 +1 来指向最后一个字符的下一个位置,作为 end
    int count_of_l = std::count(sentence, sentence + sizeof(sentence) - 1, to_find);
    std::cout << "The character '" << to_find << "' appears " << count_of_l << " times." << std::endl;
    return 0;
}

输出:

The character 'l' appears 3 times.

(注意:sizeof(sentence) 会计算整个数组的大小,包括空字符 \0,如果字符串不以 \0 这个方法会越界。)

c语言stlcount
(图片来源网络,侵删)

示例 3:使用 std::string

std::string 也支持迭代器,所以可以直接使用。

#include <iostream>
#include <string>
#include <algorithm>
int main() {
    std::text = "abracadabra";
    char char_to_find = 'a';
    int count_a = std::count(text.begin(), text.end(), char_to_find);
    std::cout << "The character '" << char_to_find << "' appears " << count_a << " times." << std::endl;
    return 0;
}

输出:

The character 'a' appears 5 times.

示例 4:使用 std::count_if (带自定义条件)

假设我们想统计一个整数列表中所有偶数的数量。

#include <iostream>
#include <vector>
#include <algorithm> // 包含 std::count_if
// 自定义谓词函数:判断一个数是否为偶数
bool is_even(int n) {
    return (n % 2) == 0;
}
int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    // 使用 lambda 表达式作为谓词
    // lambda 是一个匿名的内联函数,在这里更简洁
    int count_even = std::count_if(numbers.begin(), numbers.end(), [](int n) {
        return (n % 2) == 0;
    });
    std::cout << "There are " << count_even << " even numbers in the vector." << std::endl;
    return 0;
}

输出:

There are 5 even numbers in the vector.

与 C 语言实现的对比

在 C 语言中,你需要手动编写循环来实现类似的功能,这展示了 C++ STL 在代码简洁性和可读性上的优势。

C++ std::count 版本:

std::vector<int> v = {1, 2, 3, 2, 2};
int c = std::count(v.begin(), v.end(), 2);

C 语言手动实现版本:

#include <stdio.h>
int count_occurrences(const int* arr, int size, int value) {
    int count = 0;
    for (int i = 0; i < size; ++i) {
        if (arr[i] == value) {
            count++;
        }
    }
    return count;
}
int main() {
    int numbers[] = {1, 2, 3, 2, 2};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    int count = count_occurrences(numbers, size, 2);
    printf("Found %d times.\n", count); // 输出 Found 3 times.
    return 0;
}
  • std::count 是 C++ 的,不是 C 语言的。
  • 它位于 <algorithm> 头文件中。
  • 通过迭代器工作,具有很好的通用性,可用于各种标准容器和 C 风格数组。
  • 提供了 std::count(查找值)和 std::count_if(按条件计数)两种形式。
  • 使用 std::count 可以写出更简洁、更易读、更不易出错的代码,是现代 C++ 编程的基石之一。
-- 展开阅读全文 --
头像
织梦栏目错位原因何在?
« 上一篇 04-20
dede如何修改导航栏菜单数量上限?
下一篇 » 04-20

相关文章

取消
微信二维码
支付宝二维码

目录[+]