0
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <map>

using namespace std;

int main()
{
    ifstream fin;
    fin.open("myTextFile.txt");
    if ( fin.fail()){
        cout << "Could not open input file.";
        exit(1);
    }

    string next;
    map <string, int> words;
    while (fin >> next){
        words[next]++;
    }
    cout << "\n\n" << "Number of words: " << words[next] << endl;

    fin.close();
    fin.open("myTextFile.txt");
    while (fin >> next){
        cout << next << ": " << words[next] << endl;
    }

    fin.close();
    return 0;
}

私の主な問題は、単語が複数回出現すると、それも複数回リストされることです。つまり、テキストが "hello hello" で始まる場合、cout は "hello: 2" '\n' "hello: 2" を生成します。

また、ファイルを閉じてから、しばらくの間ファイルを再度開く必要はありません。最後のwhileループからまだファイルの最後にあるようです。

4

3 に答える 3

2

ファイルを再度開く必要はありません。

for (auto i = words.begin(); i != words.end(); i++)
{
  cout << i->first << " : " << i->second << endl;
}

またはより単純な:

for (const auto &i : words)
{
  cout << i.first << " : " << i.second << endl;
}
于 2013-03-18T15:25:47.943 に答える
2

マップを繰り返し処理する必要があり、ファイルを 2 度目に開く必要はありません。

ここで提供されているコード サンプルを見てください。

編集: ここでは、マップを反復処理するコード サンプルを示します。

// map::begin/end
#include <iostream>
#include <map>

int main ()
{
  std::map<char,int> mymap;
  std::map<char,int>::iterator it;

  mymap['b'] = 100;
  mymap['a'] = 200;
  mymap['c'] = 300;

  // show content:
  for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
    std::cout << it->first << " => " << it->second << '\n';

  return 0;
}

出力は次のとおりです。

a => 200
b => 100
c => 300
于 2013-03-18T15:24:03.510 に答える
0

マップを設定した後、マップを反復処理する必要があり、ファイルを再度開く必要はありません。これは簡単な例です。

int main()
{
  std::map<std::string, int> m1 ;

  m1["hello"] = 2 ;
  m1["world"] = 4 ;

  for( const auto &entry : m1 )
  {
    std::cout << entry.first << " : " << entry.second << std::endl ;
  }
}

予想される出力は次のようになります。

hello : 2
world : 4
于 2013-03-18T15:26:33.227 に答える