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

Accessing a pointer to a vector c++

本文关键字:c++ 指针 访问      更新时间:2023-10-16

我在访问以下向量时遇到问题。我是向量的新手,所以这可能是我做错的一个小语法事情。这是代码....

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;

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

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

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

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

void spellCheck(vector<string>& fileRead)

那么它只是:

fileRead[n].c_str()

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

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

两个访问选项:

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

改进方法的一种选择

  • 按引用传递

你可以像这样通过引用传递文件读取:

void spellCheck(vector<string> & fileRead)

或者当你像这样使用它时添加一个derefere:

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