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 に答える