1

異なるプラットフォームの STL マップで find() を使用すると問題が発生するようです。これが私のコードです。

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <map>

using namespace std;

void constructDictionary(map<string,bool> &dict);
bool isInDictionary(string word, map<string,bool> &dict);

int main(void)
{

    map<string, bool> dictionary;
    constructDictionary(dictionary);
    map<string, bool>::iterator it = dictionary.begin();

    while(it != dictionary.end()){
        cout << it->first <<endl;
        it++;
    }

    string word;
    while(true){
        cout << "Enter a word to look up: " << endl;
        cin >> word;
        if(isInDictionary(word, dictionary))
            cout << word << " exists in the dictionary." << endl;
        else
            cout << word << " cannot be found in the dictionary." << endl;
    }

    return 0;
}

void constructDictionary(map<string,bool> &dict)
{
    ifstream wordListFile;
    wordListFile.open("dictionaryList.txt");
    string line;

    while(!wordListFile.eof()){
        getline(wordListFile, line);
        dict.insert(pair<string,bool>(line, true));
    }

    wordListFile.close();
}

bool isInDictionary(string word, map<string,bool> &dict)
{
    if(dict.find(word) != dict.end())
        return true;
    else
        return false;
}

isInDictionary()Windows で Visual Studio を使用してコンパイルした場合は正常に動作しますが、ubuntu および g++ では、これはマップに最後に作成されたエントリに対してのみ機能します。私が照会する他の単語はすべて false を返します。この動作の矛盾がわかりません。どちらの場合も、main の先頭にある while ステートメントは、マップ内のすべてを正しく出力して、すべてがそこにあることを証明します。

何か案は?ありがとうございました。

4

2 に答える 2

3
  • while (!eof) は間違っています。使用するwhile (getline(...))
  • Windows linefeed を処理する必要があります\r\n。あなたの辞書はおそらくウィンドウで生成され、最後の行には改行がないため、最後の行を除くすべての単語の最後に隠し\rがあります。
于 2011-02-28T09:42:31.097 に答える
2

入力ファイルの getline と行末にエラーがありますか? \rLinux では、各単語にエクストラが追加されていることに気付くかもしれません。

どの単語にもスペースが含まれていないと仮定すると、次を使用するだけでこれを回避できます。

std::string word;
while( wordListFile >> word )
{
   if( !word.empty() )
   {
       // do the insert
   }
}

getline を使用することもできますが、両端の文字列を「トリム」します。残念ながら、標準のトリム機能はありません。いくつかの実装があります。

エントリがある場合は常に true であるこの追加の「bool」の代わりに、おそらく std::set をコレクション タイプとして使用する必要があります。

于 2011-02-28T09:41:11.003 に答える