Home > Article > Backend Development > Can Iterators from Different Containers be Compared in C ?
Comparing Iterators from Different Containers
In C , it is important to understand the principles governing iterator comparison when dealing with different containers. The question arises: "Is it acceptable to compare iterators from distinct containers?"
To answer this, we refer to the C 11 standard (n3337):
Since RandomAccessIterator inherits the requirements of ForwardIterator, it follows that comparing iterators from different containers is undefined behavior.
The LWG issue #446 specifically addresses this issue and proposes the following amendment 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 is undefined, unless explicitly described otherwise."
This amendment highlights that comparing iterators from different containers, unless they are subranges of a common range, is undefined behavior.
The above is the detailed content of Can Iterators from Different Containers be Compared in C ?. For more information, please follow other related articles on the PHP Chinese website!