访问向量C++的指针

访问向量C++的指针,c++,function,pointers,vector,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: "&l

我无法访问以下向量。我不熟悉向量,所以这可能是我做错的一个小语法。这是代码

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);
}


问题似乎是,因为它以指针的形式存在,当前用于访问它的语法无效。

您可以使用一元*从向量*获取向量:

cout << (*fileRead)[i] << "Not found" << endl;
在指向向量的指针上使用[]将不会调用std::vector::operator[]。若要根据需要调用std::vector::operator[],必须具有向量,而不是向量指针

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

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

无效拼写检查向量和文件读取

那就是:


fileRead[n].c_str

您可以按如下方式通过引用传递fileRead:

void spellCheck(vector<string> & fileRead)
if(WordCmp( (*fileRead)[i]->c_str(), dict[j].c_str()) != 0)
访问的两个选项:

*fileRead[i] fileRead->operator[]i 改进方法的一个选择

参照
你为什么不传递一个引用而不是指针?我想你的意思是vector&fileRead?@cHao是的。谢谢复制并粘贴了方法签名,但忘记更改它>。
void spellCheck(vector<string> & fileRead)
if(WordCmp( (*fileRead)[i]->c_str(), dict[j].c_str()) != 0)