+ 1

iterator of map | ++ vs += 1

Refer code below: https://www.sololearn.com/en/compiler-playground/c4K0LmgGspgf It works fine and just curious why itr++ works but changing it to itr = itr + 1 into for loop does not work?

20th Jan 2025, 4:01 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Réponses
+ 3
It is because of operator overloading. The itr++, ++itr, and itr+=n operators have been specifically overloaded to advance iterators. However, itr = itr + 1 only works if the iterator is a basic pointer. For any more complex iterator, basic math operations are undefined. This is similar to how the + operator is overloaded to do addition for numbers, but also do concatenation for strings.
20th Jan 2025, 9:23 PM
Shardis Wolfe
+ 2
I meant itr+=n as the += operator. The n is there to represent any number. itr+=1 is the same as itr++ and ++itr in that they all advance the iterator once. But you can also use other numbers to advance the iterator further. itr+=2 would advance the iterator 2 spots.
21st Jan 2025, 11:26 AM
Shardis Wolfe
0
Thanks a lot..! I got your point except overloading of itr+=n? Do you mean itr += 1 and itr+=n is a different overloaded function? Is this possible? I am clear that itr++ and ++itr is overloaded and makes sense. +n version is confusing to me. It would be good to know more on this
21st Jan 2025, 6:54 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Thanks
21st Jan 2025, 11:38 AM
Ketan Lalcheta
Ketan Lalcheta - avatar