访问指向向量c ++的指针

时间:2012-06-03 08:02:09

标签: c++ function pointers vector

我无法访问以下矢量。我是向量的新手,所以这可能是一个很小的语法,我做错了。这是代码......

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 个答案:

答案 0 :(得分:5)

在指向向量的指针上使用[]将不会调用std::vector::operator[]。要根据需要调用std::vector::operator[],您必须有一个向量,而不是向量指针。

使用指向向量的指针访问向量的第n个元素的语法是:(*fileRead)[n].c_str()

但是,您应该只传递对向量的引用:

void spellCheck(vector<string>& fileRead)

然后就是:

fileRead[n].c_str()

答案 1 :(得分:1)

你可以使用一元*来获得一个矢量&amp;来自矢量*:

cout << (*fileRead)[i] << "Not found" << endl;

答案 2 :(得分:1)

两种访问选项:

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

改进方法的一个选择

  • 通过引用传递

答案 3 :(得分:0)

您可以通过引用传递fileRead,如下所示:

void spellCheck(vector<string> & fileRead)

或者在使用它时添加一个dereferece:

if(WordCmp( (*fileRead)[i]->c_str(), dict[j].c_str()) != 0)
相关问题