Home  >  Article  >  Backend Development  >  Is Comparing Iterators from Different Containers in C Defined Behavior?

Is Comparing Iterators from Different Containers in C Defined Behavior?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 06:03:30696browse

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:

  • Iterators are considered reachable from each other if repeated applications of the increment operator ( ) result in equality.
  • Iterators refer to elements of the same sequence if they are reachable from each other.

Comparing Iterators from Different Containers:

  • For forward iterators, the comparison of iterators is only defined if they belong to the same underlying sequence.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn