Home > Article > Backend Development > Can You Compare Iterators from Different Containers in C ?
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:
<code class="cpp">std::vector<int> foo; std::vector<int> bar; std::cout << (foo.begin() == bar.begin());</code>
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 .
The above is the detailed content of Can You Compare Iterators from Different Containers in C ?. For more information, please follow other related articles on the PHP Chinese website!