我是C++的新手。我正在使用g++编译器。我试图学习C++中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++;
}
}
最佳答案
更新
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),则*current
指向实际对象(x或y)是不是指针的对象,因此需要调用(*current).x
。如果不取消引用
current
迭代器,则可以调用operator->
引用实际对象。还要注意
operator->
和operator*
具有不同的优先级,请参阅C++ Operator Precedence。如果将
XY
指针存储在std::list中,则应通过以下方式使用迭代器: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;
关于c++ - 如何使用STL迭代器处理结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19131414/