Failing to use a vector iterator, c++

2019-08-01 06:01发布

问题:

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;

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

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

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

*p1->print();

I get the next error:

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

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!

回答1:

The desired result would be achieved by

(*p1)->print();

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



回答2:

You probably want/need (*p1)->print(); As-is, it'll parse as if you'd written *(p1->print());

Chances are about 20:1 you'd really be better off storing Students instead of Student *s.

Once you've fixed that, you probably want to get rid of Student::print() and instead provide std::ostream &operator<<(std::ostream &, Student const &);. With that in place, you can do something like:

std::cout << *p1;

and (for example) printing your entire array works out to something like:

std::copy(students.begin(), students.end(), 
          std::ostream_iterator<Student>(std::cout, "\n"));


回答3:

p1 is an iterator and for the precedence rule the compiler is interpreting it like:

*(p1->print());

But what you want is:

(*p1)->print();