2013-03-17 51 views
0

我試圖訪問C++中的迭代器中的結構元素,但編譯器只是給了我一個結構不包含該元素的錯誤。我試圖做到以下幾點:在迭代器問題中訪問一個結構C++

typedef struct 
{ 
    string str; 
    int frequenzy; 
} word; 

bool isPresent = false; 

for(std::vector<word>::iterator itr=words.begin(); itr!=words.end(); ++itr) 
{ 
    if(*itr.str.compare(currentWord)==0){ 
    isPresent = true; 
    *itr.frequenzy++; 
    } 
} 

我收到以下消息:

lab7.cc: In function 'int main()': 
lab7.cc:27:13: error: 'std::vector<word>::iterator' has no member named 'str' 
lab7.cc:29:11: error: 'std::vector<word>::iterator' has no member named 'frequen 
zy' 

爲什麼不是這可能嗎?

回答

6

你或許應該重寫for循環體是這樣的:

if (itr->str.compare(currentWord)==0) 
//  ^^ 
{ 
    isPresent = true; 
    itr->frequenzy++; 
//  ^^ 
} 

.操作符比*運營商更高的優先級。因此,如果你真的想使用這兩個運營商,你應該重寫上述這種方式:

if ((*itr).str.compare(currentWord)==0) 
// ^^^^^^^ 
{ 
    isPresent = true; 
    (*itr).frequenzy++; 
// ^^^^^^^ 
}