+ 2
Comparing two iterator of different containers
Hi I was informed that comparing two iterator of different containers will either crash or result into undefined behaviour. I have a case where above statement is false. Please refer code below: I know iterator is almost a pointer and points to actual data within container. As v1 and v2 is different, itr1 and itr2 points to different memory location. Hence, itr1 == itr2 will be false and same is shown in output as well. So, just want to confirm that this output is always same and it is not undefined behaviour. https://sololearn.com/compiler-playground/c69473vKMc7H/?ref=app
3 Answers
+ 2
Ketan Lalcheta It depends on the compiler settings and how the iterator for the container implements the overload of the == operator.
Most compilers will usually yield a compiler warning about the comparison.
If the compiler is set to be forgiving, it might allow the comparison but it will always be false.
Since each container represents a different memory space, it will always be impossible for the 2 iterators to ever be equal.
+ 2
Your implementation is a valid way to check if two iterators are the same and it cannot lead to undefined behaviour
If you're doing any container operations like push_back() etc, then you should always remember to recheck v1 and v2 again
0
Thanks RuntimeTerror and Shardis Wolfe