STL 计数(count,count_if)的用法

本文展示了一个使用 C++ 标准模板库 (STL) 的示例程序,包括 vector 和 set 容器的使用,以及算法如 generate_n、count 和 sort 的应用。通过 CharGen 生成器填充 vector,并统计每个字符出现的次数,最后对 vector 进行排序。
#include <algorithm>
#include <functional>
#include <set>
#include <iterator>
#include <vector>
#include "Generators.h"//见同类填充与生成章节
#include "PrintSequence.h"
using namespace std;

int main()
{
	vector<char> v;
	generate_n(back_inserter(v), 50, CharGen());
	print(v.begin(), v.end(), "v", "");

	set<char> cs(v.begin(), v.end());
	typedef set<char>::iterator sci;
	for(sci it = cs.begin(); it != cs.end(); it++)
	{
		int n = count(v.begin(), v.end(), *it);
		cout << *it << ":" << n << ", ";
	}

	int lc = count_if(v.begin(), v.end(),
		bind2nd(greater<char>(), 'a'));
	cout << "\nLowercase letters: " << lc << endl;
	sort(v.begin(), v.end());
	print(v.begin(), v.end(), "sorted", "");
	system("pause");
	return 0;
}



结果如下:


在C++ STL中,count函数有不同的应用场景和使用方式: ### 在集合(set)中的使用 在C++ STL的集合(set)中,count()函数是内置函数,用于计数在与函数关联的集合中找到自变量的次数。由于集合中所有值都是唯一的,因此该函数只能返回两个值0或1,意味着该集合中的一个值最多只会出现一次。示例代码如下: ```cpp #include <iostream> #include <set> int main() { std::set<int> mySet = {1, 2, 3, 4, 5}; int elementToFind = 3; int count = mySet.count(elementToFind); std::cout << "Element " << elementToFind << " appears " << count << " times in the set." << std::endl; return 0; } ``` ### 作为泛化模板函数的使用 count函数的泛化版本用断言指定的条件代替等于一个指定的值。不过,当要统计满足特定条件的元素个数时,通常会使用count_if函数。count_if函数的参数为count_if(first, last, value, comp),其中first为首迭代器,last为末迭代器,value为要查询的元素,comp为比较函数 [^2]。以下是count_if函数的STL源代码: ```cpp template <class InputIterator, class Predicate> ptrdiff_t count_if ( InputIterator first, InputIterator last, Predicate pred ) { ptrdiff_t ret = 0; while (first != last) if (pred(*first++)) ++ret; return ret; } ``` 示例代码,统计1 - 10中奇数的个数: ```cpp #include <iostream> #include <vector> #include <algorithm> bool isOdd(int num) { return num % 2 != 0; } int main() { std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int oddCount = std::count_if(numbers.begin(), numbers.end(), isOdd); std::cout << "There are " << oddCount << " odd numbers in the vector." << std::endl; return 0; } ``` ### 在map和unordered_map中的使用 当用map或者unordered_map去存储某个元素出现的次数时,count方法只是一个先行的判断条件,用于判断元素是否存在,而不是统计元素的个数。如果要获取元素的个数,应该用下标描述,例如temp[num] [^4]。示例代码: ```cpp #include <iostream> #include <map> int main() { std::map<int, int> myMap; myMap[1] = 3; myMap[2] = 2; int num = 1; if (myMap.count(num)) { std::cout << "Element " << num << " exists and its count is " << myMap[num] << std::endl; } else { std::cout << "Element " << num << " does not exist in the map." << std::endl; } return 0; } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值