0

次のベクターにアクセスできません。ベクトルは初めてなので、これはおそらく構文上の小さな間違いです。ここにコードがあります....

void spellCheck(vector<string> * fileRead)
{   
    string fileName = "/usr/dict/words";
    vector<string> dict;        // Stores file

    // Open the words text file
    cout << "Opening: "<< fileName << " for read" << endl;

    ifstream fin;
    fin.open(fileName.c_str());

    if(!fin.good())
    {
        cerr << "Error: File could not be opened" << endl;
        exit(1);
    }
    // Reads all words into a vector
    while(!fin.eof())
    {
        string temp;
        fin >> temp;
        dict.push_back(temp);
    }

    cout << "Making comparisons…" << endl;
    // Go through each word in vector
    for(int i=0; i < fileRead->size(); i++)
    {
        bool found = false;

        // Go through and match it with a dictionary word
        for(int j= 0; j < dict.size(); j++)
        {   
            if(WordCmp(fileRead[i]->c_str(), dict[j].c_str()) != 0)
            {
                found = true;   
            }
        }

        if(found == false)
        {
            cout << fileRead[i] << "Not found" << endl; 
        }
    }
}

int WordCmp(char* Word1, char* Word2)
{
    if(!strcmp(Word1,Word2))
        return 0;
    if(Word1[0] != Word2[0])
        return 100;
    float AveWordLen = ((strlen(Word1) + strlen(Word2)) / 2.0);

    return int(NumUniqueChars(Word1,Word2)/ AveWordLen * 100);
}

エラーは行にあります

if(WordCmp(fileRead[i]->c_str(), dict[j].c_str()) != 0)

cout << fileRead[i] << "Not found" << endl;

問題は、ポインターの形式であるため、アクセスに使用している現在の構文が無効になるためです。

4

4 に答える 4

5

[]ベクトルへのポインターで使用しても、 は呼び出されませんstd::vector::operator[]。必要に応じて呼び出すstd::vector::operator[]には、ベクトル ポインターではなく、ベクトルが必要です。

ベクトルへのポインターを使用してベクトルの n 番目の要素にアクセスする構文は、次のようになります(*fileRead)[n].c_str()

ただし、ベクトルへの参照を渡す必要があります。

void spellCheck(vector<string>& fileRead)

それはただです:

fileRead[n].c_str()

于 2012-06-03T08:05:38.500 に答える
1

単項 * を使用して、vector から vector& を取得できます*:

cout << (*fileRead)[i] << "Not found" << endl;
于 2012-06-03T08:05:31.977 に答える
1

アクセスするための 2 つのオプション:

  • (*fileRead)[i]
  • fileRead->operator[](i)

メソッドを改善するための 1 つのオプション

  • 参照渡し
于 2012-06-03T08:11:22.647 に答える
0

次のように、参照によって fileRead を渡すことができます。

void spellCheck(vector<string> & fileRead)

または、次のように使用するときに逆参照を追加します。

if(WordCmp( (*fileRead)[i]->c_str(), dict[j].c_str()) != 0)
于 2012-06-03T08:08:23.490 に答える