简单说一下代码。
函数用函数模板,缺点是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;
}
}