0

各行に単語 ID、単語、頻度が空白で区切られた辞書ファイルを読み込もうとしました。問題は、単語を格納するために使用されるマップが同じ値を持つことが判明したことです。あなたが私を助けることができれば、私はとても感謝しています.

typedef struct{
    int id;
    int count;
    char* word;
} WORD;

//read file
std::map<int, WORD*> readWordMap(char* file_name)
{
    std::ifstream infile(file_name, std::ifstream::in);
    std::cout<<"word map read file:"<<file_name<<std::endl;
    if (! infile) {
        std::cerr<<"oops! unable to open file "<<file_name<<std::endl;
        exit(-1);
     }
     std::map<int, WORD*> map;
     std::vector<std::string> tokens;
     std::string line;
     char word[100];
     int size;
     while (std::getline(infile, line)) {
         size =  (int)split(line, tokens, ' ');
         WORD* entry = (WORD*) malloc(sizeof(WORD*));
         entry->id = atoi(tokens[0].c_str());
         entry->count = atoi(tokens[2].c_str());
         strcpy(word, tokens[1].c_str());
         entry->word = word;

         map[entry->id] = entry;
         std::cout<< entry->id<<" "<<entry->word<<" "<<entry->count<<std::endl;

      }
      infile.close();
      std::cout<<map.size()<<std::endl;
      std::map<int, WORD*>::const_iterator it;
      for (it = map.begin(); it != map.end(); it++) {
           std::cout<<(it->first)<<" "<<(it->second->word)<<std::endl;

      }

      return map;
}

//split string by a delimiter
size_t split(const std::string &txt, std::vector<std::string> &strs, char ch)
{
    size_t pos = txt.find( ch );
    size_t initialPos = 0;
    strs.clear();

    while( pos != std::string::npos ) {
        strs.push_back( txt.substr( initialPos, pos - initialPos + 1 ) );
        initialPos = pos + 1;

        pos = txt.find( ch, initialPos );
    } 

   strs.push_back( txt.substr( initialPos, std::min( pos, txt.size() ) - initialPos + 1      ) );

   return strs.size();
}

データファイル:

2 I  1
3 gave  1
4 him  1
5 the  3
6 book  3
7 .  3
8 He  2
9 read  1
10 loved  1

結果:

2 I  1
3 gave  1
4 him  1
5 the  3
6 book  3
7 .  3
8 He  2
9 read  1
10 loved  1
map size:9
2 loved 
3 loved 
4 loved 
5 loved 
6 loved 
7 loved 
8 loved 
9 loved 
10 loved 
4

2 に答える 2

1

WORD::wordbefore にメモリを割り当てるのを忘れていますstrcpychar word[100]そして、マップのすべてのアイテムに同じ住所を割り当てています。

 

std::stringまた、C スタイルの文字列の代わりに使用することをお勧めします。さらにstd::stoi、文字列を整数に変換するために使用できます。これを試して:

struct WORD{
    int id;
    int count;
    std::string word;
};

std::map<int, WORD> readWordMap(const std::string &file_name)
{
     ...
     std::map<int, WORD> map;
     ...

     while (std::getline(infile, line)) {
         ...

         WORD entry;
         entry.id = std::stoi(tokens[0]);
         entry.count = std::stoi(tokens[2]);
         entry.word = tokens[1];

         map[entry.id] = entry;

         ...
      }
      infile.close();
      ...
}
于 2013-05-16T20:49:13.570 に答える