0

我需要在字符串数组中找到出现次数最多的元素。我不确定该怎么做,因为我对此没有太多经验。我不知道指针/哈希表。

我已经为整数做了这个,但我不能让它适用于字符串。

我的版本:

#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;
    }

感谢您在字符串数组中查找最频繁出现的元素的任何帮助!

4

2 回答 2

1

首先,考虑使用像向量这样的 C++ 容器而不是普通数组。(如果需要,搜索“数组到向量”或类似的在它们之间进行转换。)

然后,如果你可以使用 C++11,你可以做这样的事情(如果没有 C++11,它会变得有点冗长,但仍然可行):

std::string most_occurred(const std::vector<std::string> &vec) {
  std::map<std::string,unsigned long> str_map;
  for (const auto &str : vec)
    ++str_map[str];

  typedef decltype(std::pair<std::string,unsigned long>()) pair_type;

  auto comp = [](const pair_type &pair1, const pair_type &pair2) -> bool {
    return pair1.second < pair2.second; };
  return std::max_element(str_map.cbegin(), str_map.cend(), comp)->first;
}

这是与旧 C++ 兼容的版本

bool comp(const std::pair<std::string,unsigned long> &pair1,
          const std::pair<std::string,unsigned long> &pair2) {
  return pair1.second < pair2.second;
}

std::string most_occurred(const std::vector<std::string> &vec) {
  std::map<std::string,unsigned long> str_map;
  for (std::vector<std::string>::const_iterator it = vec.begin();
       it != vec.end(); ++it)
    ++str_map[*it];
  return std::max_element(str_map.begin(), str_map.end(), comp)->first;
}
于 2013-02-24T20:12:38.303 回答
0

您可以考虑使用字符串向量并使用映射来计算出现次数:

#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;
} 

就优雅和效率而言,这个解决方案可能不是最好的,但它应该给出这个想法。

于 2013-02-24T20:28:25.703 回答