2012-06-03 171 views
0

Im无法访问以下矢量。我对向量新来说,所以这可能是一个小的语法错误。这里是代码....访问指向矢量的指针C++

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

为什么你不通过引用而不是指针? – Mat

回答

1

可以使用一元*从*矢量得到的矢量&:

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

上的指针使用[]的矢量不会叫std::vector::operator[]。如果您想要调用std::vector::operator[],则必须具有矢量,而不是矢量指针。

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

然而,你应该只传递给矢量参考:

void spellCheck(vector<string>& fileRead)

然后,它只是:

fileRead[n].c_str()

+0

我假设你的意思是'矢量&fileRead'? – cHao

+0

@cHao是的。谢谢!复制并粘贴方法签名,但忘记更改>。<。 – Corbin

0

您可以通过FILEREAD通过引用这样的:

void spellCheck(vector<string> & fileRead) 

或添加,当你使用这样一个dereferece:

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

两个选项访问:

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

一个选项,以改善方法

  • 通过参考