Home > Article > Backend Development > Is It Valid to Compare Iterators from Different Containers in C ?
Comparing Iterators from Distinct Containers
When working with containers, it's essential to understand the implications of comparing iterators from different containers. The question arises: is it permissible to compare iterators belonging to distinct containers?
Consider the following code:
<code class="cpp">std::vector<int> foo; std::vector<int> bar; std::cout << (foo.begin() == bar.begin());</code>
Will the expression foo.begin() == bar.begin() yield false or lead to undefined behavior?
Delving into the C 11 standard (n3337) can shed light on this dilemma:
Iterators within the Same Sequence
Comparing Iterators from Different Containers
Given these requirements, comparing iterators from different containers is undefined behavior.
LWG Issue #446
LWG issue #446 explicitly addresses this question, proposing the following addition 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 r1 and r2 [...] which are not subranges of one common range is undefined, unless explicitly described otherwise."
In conclusion, comparing iterators from distinct containers is undefined behavior, and it's crucial to adhere to this constraint when writing custom iterators and manipulating containers in your code.
The above is the detailed content of Is It Valid to Compare Iterators from Different Containers in C ?. For more information, please follow other related articles on the PHP Chinese website!