1

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!

3 Answers 3

10

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

Sign up to request clarification or add additional context in comments.

Comments

3

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")); 

1 Comment

@Potatoswatter: Just calling the odds.
1

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

*(p1->print()); 

But what you want is:

(*p1)->print(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.