C++ 实现统计vector中各个元素的个数(去重)

在这里插入图片描述
简单说一下代码。
函数用函数模板,缺点是double或float类型一般比较会有一个误差值,另外map的排序不可避免。这里提示一下,可以根据具体项目来修改,若不要map排序,则可以考虑用vector来存储pair<class,class>,以达到只去重的目的; 或者用unordered_map来存。
具体使用可看main函数使用示例。

#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;

template<typename T>
inline int equals(T a, T b){
	return a == b;
}

///     作者:BostonAlen								///	
///     功能:获取数组中元素的个数					///  
///		参数1:需统计的数组							///  
///     参数2:保存结果,元素以及对应元素对应个数		///  
template<typename T>
void check(vector<T> &src, map<T,int> &dst)
{
	for (size_t i = 0; i < src.size(); ++i) {
		T checkStr = src[i];
		int flag = 0;
		for (size_t j = 0; j < i; ++j) {
			if (equals(checkStr, src[j])) {
				flag = 1;
				break;
			}
		}
		if (!flag) {
			int count = 1;
			for (size_t j = i + 1; j < src.size(); ++j) {
				if (equals(checkStr, src[j])){
					++count;
				}
			}
			dst.insert(pair<T, int>(checkStr, count));
		}
	}
}
int main()
{
	//string
	vector<string> vs = { "蓝方飞机", "平台飞机", "蓝方飞机", "蓝方飞机", "平台飞机", "轰炸机", "蓝方飞机", "轰炸机", "轰炸机", "高功率", "高功率", "平台飞机" };
	map<string, int> vsDst;
	check(vs, vsDst);
	map<string, int>::iterator it1;
	cout << "/*******String:********/" << endl;
	for (it1 = vsDst.begin(); it1 != vsDst.end(); ++it1)
	{
		cout << (*it1).first << " 的个数为 :" << (*it1).second << endl;
	}

	//int
	vector<int> vi = { 212, 201, 189, 212, 213, 189, 212, 201, 187, 212, 211, 189 };
	map<int, int> viDst;
	check(vi, viDst);
	map<int, int>::iterator it2;
	cout << endl;
	cout << "/*******Int:*******/" << endl;

	for (it2 = viDst.begin(); it2 != viDst.end(); ++it2)
	{
		cout << (*it2).first << " 的个数为 :" << (*it2).second << endl;
	}

	//double
	vector<double> vd = { 2.12, 2.01, 1.89, 2.12, 2.13, 1.89, 2.12, 2.01, 1.87, 2.12, 2.11, 1.89 };
	map<double, int> vdDst;
	check(vd, vdDst);
	map<double, int>::iterator it3;
	cout << endl;
	cout << "/*******double:*******/" << endl;
	for (it3 = vdDst.begin(); it3 != vdDst.end(); ++it3)
	{
		cout << (*it3).first << " 的个数为 :" << (*it3).second << endl;

	}
}

在这里插入图片描述

  • 7
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值