如何使用STL迭代器处理结构 我是C++新手。我正在使用g++编译器。我正在努力学习STL图书馆的C++操作。在工作中,我发现这段代码有一些问题。请解释错误的原因以及如何处理错误 #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++; } } #包括 #包括 使用名称空间std; 类型定义结构corrd{ int x; int-y; }XY; int main() { 列表值; 列表::迭代器当前; XY数据[10]; 对于(int i=0;i

如何使用STL迭代器处理结构 我是C++新手。我正在使用g++编译器。我正在努力学习STL图书馆的C++操作。在工作中,我发现这段代码有一些问题。请解释错误的原因以及如何处理错误 #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++; } } #包括 #包括 使用名称空间std; 类型定义结构corrd{ int x; int-y; }XY; int main() { 列表值; 列表::迭代器当前; XY数据[10]; 对于(int i=0;i,c++,C++,更新 您可以使用*current将迭代器“转换”为它包含的对象。因为您有XY结构(不是指针而是值),所以您应该编写: cout<<"X coord:"<<(*current).x<<endl; cout<<"Y coord:"<<(*current).y<<endl; cout迭代器有点像泛化指针(它的语义与*和->相同)。您正确地使用了->来访问迭代器指向的结构的成员。该成员的类型为int,因此没有什么可以取消引用的。因

更新

您可以使用*current将迭代器“转换”为它包含的对象。因为您有XY结构(不是指针而是值),所以您应该编写:

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

cout迭代器有点像泛化指针(它的语义与
*
->
相同)。您正确地使用了
->
来访问迭代器指向的结构的成员。该成员的类型为
int
,因此没有什么可以取消引用的。因此,只需执行以下操作:

cout<<"X coord:"<<current->x<<endl;
cout<<"Y coord:"<<current->y<<endl;
cout错误“一元数'*'(有'int')的无效类型参数”来自以下表达式:
*current->x
。一元数的
int
参数是什么?
current->x
当然,如果您查找
x
的声明,您会看到它是
int

因此,您可以编写
5*current->x
,但这是乘法。一元
*
,取消引用,需要右侧的(智能)指针或迭代器


请注意,
->
的优先级高于一元
*
,因此代码不会被解析为
(*current)->x
,而是被解析为
*(current->x)

,换句话说,由于操作顺序,它会失败。不,它失败是因为有两个解引用(都是*和->)不要在使用前声明变量,在第一次使用时声明它们。
cout<<"X coord:"<<current->x<<endl;
cout<<"Y coord:"<<current->y<<endl;
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;
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;