一 写在前面
- C++ 标准库算法主要定义于头文件 < algorithm >, 一些用于数值处理的算法定义于头文件< numeric > 。
- 本文介绍 非更易型算法 中的用于 元素计数 的两种算法:std::cout 和std::count_if。
二 std::count 和 std::count_if
- 返回范围 [first, last) 中满足特定判别标准的元素数。
template< class InputIt, class T >
typename iterator_traits<InputIt>::difference_type
count( InputIt first, InputIt last, const T &value );(1)(C++20 前)
template< class InputIt, class T >
constexpr typename iterator_traits<InputIt>::difference_type
count( InputIt first, InputIt last, const T &value );(1)(C++20 起)
template< class ExecutionPolicy, class ForwardIt, class T >
typename iterator_traits<ForwardIt>::difference_type
count( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, const T &value );(2)(C++17 起)
template< class InputIt, class UnaryPredicate >
typename iterator_traits<InputIt>::difference_type
count_if( InputIt first, InputIt last, UnaryPredicate p );(3)(C++20 前)
template< class InputIt, class UnaryPredicate >
constexpr typename iterator_traits<InputIt>::difference_type
count_if( InputIt first, InputIt last, UnaryPredicate p );(3)(C++20 起)
template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate >
typename iterator_traits<ForwardIt>::difference_type
count_if( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPredicate p );(4)(C++17 起)
- 其中 Unary Predicate 解释请参照 C++ predicate
三 Demo
#include
#include
#include
#include
#include
template <typename C>
void fill(C& container, int begin, int end) {
for (auto i = begin; i <= end; i++) {
container.emplace_back(i);
}
}
template <typename C>
void print(const std::string& pre, C container) {
std::cout << pre;
std::copy(container.begin(), container.end(),
std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
}
bool even(int a) {
return a % 2 == 0;
}
int main() {
std::vector<int> vc;
fill(vc, 1, 9);
vc.emplace_back(9);
vc.emplace_back(9);
{
int count5 = std::count(vc.begin(), vc.end(), 5);
int count9 = std::count(vc.begin(), vc.end(), 9);
print("vc: ", vc);
std::cout << "count of 5 in vc: " << count5 << std::endl;
std::cout << "count of 9 in vc: " << count9 << std::endl;
}
{
int count = std::count_if(vc.begin(), vc.end(), even);
std::cout << "count of even numbers in vc: " << count << std::endl;
}
std::cin.get();
return 0;
}
- 说明:
- ostream_iterator 是 C++ iterator(5)reverse_iterator adaptor 提到的另外一种迭代器适配器类型。
- print 函数也可以简单通过遍历实现:
template <typename C>
void print1(const std::string& pre, C container) {
std::cout << pre;
for(auto it = container.begin(); it != container.end(); it++) {
std::cout << *it << " ";
}
std::cout << std::endl;
}
vc: 1 2 3 4 5 6 7 8 9 9 9
count of 5 in vc: 1
count of 9 in vc: 3
count of even numbers in vc: 4
四 参考
- 《C++ 标准库 第2版》
- cppreference