Comparing Iterators from Different Containers: A Cautionary Tale
In C , iterators provide a powerful mechanism for traversing collections. However, it is important to be aware of the limitations when using iterators from different containers.
The question of whether it is legal to compare iterators from different containers arises frequently. Consider the following example:
std::vector foo;
std::vector bar;
std::cout This expression may seem harmless at first glance, but it actually yields undefined behavior. According to the C 11 standard, iterators can only be compared if they refer to elements of the same sequence. Since foo and bar are two distinct vectors, their iterators are not comparable.
This behavior is further emphasized in LWG issue #446:
"The result of directly or indirectly evaluating any comparison function or the binary - operator with two iterator values as arguments that were obtained from two different ranges r1 and r2 (...) which are not subranges of one common range is undefined, unless explicitly described otherwise."
This restriction has significant implications for implementing custom iterators. If you plan to implement an operator== for your custom iterator, you must ensure that it only compares iterators that are within the same range.
Failing to adhere to this rule can lead to unexpected behavior and is ultimately detrimental to the reliability of your code. Therefore, it is crucial to keep in mind that comparing iterators from different containers is strictly prohibited in C .
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3