Home >Backend Development >C++ >Is Comparing Iterators from Different Containers in C Defined Behavior?
Comparing Iterators from Different Containers in C
In the context of custom iterator implementation, a fundamental question arises: is it permissible to compare iterators from distinct containers? Take, for instance, the following code snippet:
<code class="cpp">std::vector<int> foo; std::vector<int> bar; // Is this expression valid? foo.begin() == bar.begin();</code>
According to the C 11 standard:
Iterators within the Same Sequence:
Comparing Iterators from Different Containers:
Therefore, comparing iterators from different containers, such as foo.begin() and bar.begin() in the example above, is considered undefined behavior.
This undefined behavior stems from the fact that iterators reference specific elements within a container. When iterators belong to different containers, they cannot be assumed to point to elements in the same underlying sequence, hence their comparison yields undefined results.
LWG Issue #446:
To clarify this issue, LWG issue #446 proposed adding the following text to the standard:
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... is undefined, unless explicitly described otherwise.
This addition further emphasizes the undefined nature of comparing iterators from distinct containers.
The above is the detailed content of Is Comparing Iterators from Different Containers in C Defined Behavior?. For more information, please follow other related articles on the PHP Chinese website!