Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ iterator operator precedence issue *it.method() vs (*it).method() vs it->method()

Tags:

c++

iterator

This code won't compile:

for(vector<Box>::iterator it = shapes.end(); it >= shapes.begin(); --it){
    *it.update(1,1);
    *it.draw();
}

It claims:

main.cpp:80:17: error: ‘std::vector<Box>::iterator’ has no member named ‘update’
main.cpp:81:17: error: ‘std::vector<Box>::iterator’ has no member named ‘draw’

However AFAIK, that code doesn't try and call vector::iterator.draw(), it dereferences the iterator, which should give me an object of my class box, which does have those methods. What am I doing wrong, and sorry for the awful title.

like image 984
w4etwetewtwet Avatar asked Jun 14 '26 10:06

w4etwetewtwet


2 Answers

It's a matter of operator precedence.

Operator . has higher precedence than operator *. Use parenthesis to force operator * application first.

(*it).update(1,1);
(*it).draw();

You can also use operator -> on iterators.

it->update(1,1);
it->draw();

Also see: What is the difference between the dot (.) operator and -> in C++? and cppreference: Member access operators.


@andre stated correctly that you can also use reverse iterators to iterate over a sequence in reverse order but you should use them correctly.
for(vector<Box>::reverse_iterator it = shapes.rbegin(); it != shapes.rend(); ++it)
{
  it->update(1,1);
  it->draw();
}
like image 75
Pixelchemist Avatar answered Jun 16 '26 13:06

Pixelchemist


also, to add on @Pixelchemist 's answer.

for(vector<Box>::iterator it = shapes.end(); it >= shapes.begin(); --it){
    *it.update(1,1);
    *it.draw();
}

should be:

for(vector<Box>::reverse_iterator it = shapes.rbegin(); it != shapes.rend(); ++it){
    *it.update(1,1);
    *it.draw();
}

rend and rbeing are used to iterate in reverse.

like image 29
andre Avatar answered Jun 16 '26 12:06

andre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!