字符串数组中出现次数最高的元素 [英] Element with highest occurence in array of strings
问题描述
我需要在字符串数组中找到出现次数最多的元素.我不确定该怎么做,因为我对此没有太多经验.我不知道指针/哈希表.
I need to find the element with the highest occurrence in an array of strings. I am not sure what to do, since I don't have much experience with this. I don't know pointers / hashtables.
我已经为整数完成了此操作,但是我无法使其适用于字符串.
I've already done this for integers, but I can't make it work for strings.
我的版本:
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int a[]={1,2,3,4,4,4,5};
int n = sizeof(a)/sizeof(int );
int *b=new int [n];
fill_n(b,n,0); // Put n times 0 in b
int val=0; // Value that is the most frequent
for (int i=0;i<n;i++)
if( ++b[a[i]] >= b[val])
val = a[i];
cout<<val<<endl;
delete[] b;
return 0;
}
对于在字符串数组中查找最频繁出现的元素的任何帮助,我们深表感谢!
Any help for finding the most frequently occurring element in the array of strings is appreciated!
推荐答案
You could consider using a vector of strings and to use a map to count occurrences:
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main(int argc, char *argv[])
{
vector<string> a;
map<string, int> m;
// fill a with strings
a.push_back("a");
a.push_back("b");
a.push_back("b");
a.push_back("c");
a.push_back("c");
a.push_back("c");
a.push_back("d");
a.push_back("e");
// count occurrences of every string
for (int i = 0; i < a.size(); i++)
{
map<string, int>::iterator it = m.find(a[i]);
if (it == m.end())
m.insert(pair<string, int>(a[i], 1));
else
m[a[i]] += 1;
}
// find the max
map<string, int>::iterator it = m.begin();
for (map<string, int>::iterator it2 = m.begin(); it2 != m.end(); ++it2)
{
if (it2 -> second > it -> second)
it = it2;
}
cout << it -> first << endl;
return 0;
}
就优雅和效率而言,此解决方案可能不是最佳解决方案,但应该给出想法.
This solution is probably not the best one in terms of elegance and efficiency, however it should give the idea.
这篇关于字符串数组中出现次数最高的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!