没有使用向量迭代器,c ++ [英] Failing to use a vector iterator, c++

查看:124
本文介绍了没有使用向量迭代器,c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图迭代一个向量,它包含指向Student类型对象的指针。
向量的声明如下: static vector< Student *>学生;

I'm trying to iterate over a vector holding a pointer to an object of type Student. The declaration of vector is as follow: static vector<Student*> students;

无论如何,我想在函数pickWinners()中使用迭代器:

Anyhow, I am trying to use an iterator in function pickWinners():

vector<Student*>::iterator p1 = students.begin();
vector<Student*>::iterator p2 = p1;
p2++;

据我所知,p1是指向Student的指针。但是当我尝试这个(例如):

As I understand, p1 is a pointer to a pointer to Student. But when I try this (for example):

*p1->print();

我得到下一个错误:


Hire.cpp:192:error:请求成员'print'在'* p1 .__ gnu_cxx :: __ normal_iterator <_Iterator,_Container> :: operator-> with _Iterator = Student **,_Container = std :: vector>',这是非类类型'Student *'
make: * [Hire.o]错误1

Hire.cpp:192: error: request for member ‘print’ in ‘* p1.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator-> with _Iterator = Student**, _Container = std::vector >’, which is of non-class type ‘Student*’ make: * [Hire.o] Error 1

这对我没有任何意义。我知道问题不是在print()。
我尝试了

This doesn't make any sense to me. I know the problem is not in print(). I tried

Student *student = students.at(0);
student->print();

,一切工作完美。我在这里很无能,任何想法?
谢谢!

and everything worked perfect. I'm pretty clueless here, any ideas? Thanks!

推荐答案

期望的结果将通过

(*p1)->print();

在这种情况下,代码解析为 *(p1-> print因为 operator-> 的优先级高于 operator * 例如,维基百科上的优先级表

In your case, the code parses as *(p1->print());, because operator-> has higher precedence than operator*, see for example, the precedence table on wikipedia

这篇关于没有使用向量迭代器,c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆