Home > Backend Development > C++ > body text

Is It Valid to Compare Iterators from Different Containers in C ?

Barbara Streisand
Release: 2024-11-02 09:02:29
Original
1004 people have browsed it

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>
Copy after login

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

  • Section 24.2.1 states that two iterators, i and j, are considered reachable if there exists a finite sequence of i operations that makes i equal to j.
  • If j is reachable from i, they reference elements from the same sequence.

Comparing Iterators from Different Containers

  • ForwardIterators, which include RandomAccessIterators, are subject to Section 24.2.5.
  • This section specifies that == can only be used to compare iterators over the same underlying sequence.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template