2013-10-02 46 views
2

我是C++中的新成員。我正在使用g ++編譯器。我試圖學習C++中STL庫的操作。在工作時,我在代碼中發現了一些問題。請解釋錯誤的原因以及如何照顧錯誤。如何使用STL迭代器處理結構

#include<iostream> 
#include<list> 
using namespace std; 

typedef struct corrd{ 
int x; 
int y; 
}XY; 

int main() 
{ 
list<XY> values; 
list<XY>::iterator current; 
XY data[10]; 
for(int i=0;i<10;i++) 
{ 
    data[i].x = i+10; 
    data[i].y = i+20; 
} 
for(int i=0;i<10;i++) 
{ 
    values.push_front(data[i]); 
} 
current = values.begin(); 
while(current!=values.end()) 
{ 
    cout<<"X coord:"<<*current->x<<endl;//error: invalid type argument of unary ‘*’ (have ‘int’ 
    cout<<"Y coord:"<<*current->y<<endl;//error: invalid type argument of unary ‘*’ (have ‘int’ 
    current++; 
} 
} 
+0

使用前不要聲明變量,聲明他們在* *第一次使用。 –

回答

2

更新

cout<<"X coord:"<<*current->x<<endl; 
cout<<"Y coord:"<<*current->y<<endl; 

到:

cout<<"X coord:"<<(*current).x<<endl; 
cout<<"Y coord:"<<(*current).y<<endl; 

cout<<"X coord:"<<current->x<<endl; 
cout<<"Y coord:"<<current->y<<endl; 

current是迭代器,如果您嘗試取消對它的引用(*電流),*current點真實的物體(x或y)是一個對象不是指針,所以你需要調用(*current).x

如果您不取消對current迭代器的引用,則可以調用operator->來引用真實對象。

另請注意,operator->operator*具有不同的優先級,請參閱C++ Operator Precedence

如果您存儲XY指針的std ::列表中,你應該使用迭代器是這樣的:

list<XY*> values; 
list<XY*>::iterator current; 
cout<<"X coord:"<<(*current)->x<<endl; // parentheses is needed due to Operator Precedence 
cout<<"Y coord:"<<(*current)->y<<endl; 
+1

換句話說,它由於操作順序而失敗。 – Adam

+1

不,它失敗了,因爲有兩個解除引用(包括*和 - >)而不是一個。 – MSalters

+0

好的......有了它。很好的解釋。謝謝 – Tonmoy

0

您使用*電流和「轉換」迭代反對它包含的內容。正如你所XY結構存在(不是指針,但按價值計算),你應該寫:

cout<<"X coord:"<<(*current).x<<endl; 
cout<<"Y coord:"<<(*current).y<<endl; 

(而不是 「 - >」 「」)。

另一種方法是使用迭代器的「 - >」運算符。它允許直接使用包含類型(struct或class)的成員。然後,你需要寫:

cout<<"X coord:"<<current->x<<endl; 
cout<<"Y coord:"<<current->y<<endl; 

只是刪除「*」

+0

是的,沒錯。固定 –

0

迭代器是一個有點像一個廣義指針(它具有*->相同的語義)。您正確使用->來訪問迭代器指向的結構成員。該成員的類型爲int,所以沒有什麼可以解除引用了。因此,只要做到這一點:

cout<<"X coord:"<<current->x<<endl; 
cout<<"Y coord:"<<current->y<<endl; 
0

錯誤「的一元無效的類型參數‘*’(有‘詮釋’)」來自下面的表達式:*current->x。那是什麼int一元論證*?那麼,current->x當然,如果你查詢你的x的聲明,你會發現它是一個int

所以,你可以寫5 * current->x,但這是乘法。 Unary *,解引用,需要右側的(智能)指針或迭代器。

注意->具有比一元*更高的優先級,這樣的代碼不會被解析爲(*current)->x*(current->x)