计算stl中重复元素个数的函数

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_23350817/article/details/100097881

可以使用count计算元素中重复元素个数

#include <iostream>
#include <bitset>
#include <vector>

using namespace std;

int main(int argc, char* argv)
{
	bitset<8> bt;
	bool ret = bt.any();
	if (ret) {
		cout << "True" << endl;
	}
	else {
		cout << "False" << endl;
	}

	vector<int> vec{ 1, 2, 3, 1, 2, 2, 2, 3, 3, 3, 3 };
	cout << count(vec.begin(), vec.end(), 3) << endl;
	
	while (1);

	return 0;
}

count在某些场合可以替换find使用。但是如果需要找到查找数据的位置时则必须使用find函数,count更强调查找元素出现的个数。
当如果需要清除容器中重复元素的时候,使用unique。很多场合就是先count计算是否有重复元素,如果有就先unique删除重复元素,然后使用sort对元素进行排序。

猜你喜欢

转载自blog.csdn.net/qq_23350817/article/details/100097881