Home > Backend Development > C++ > body text

Can Iterators from Different Containers be Compared in C ?

Patricia Arquette
Release: 2024-11-01 14:35:29
Original
535 people have browsed it

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):

  • General Iterator Requirements: An iterator j is reachable from an iterator i only if applying i finitely many times results in i == j. Iterators that are reachable refer to elements of the same sequence.
  • Forward Iterators and Equality: The domain of the equality operator (==) for forward iterators is restricted to iterators that originate from the same underlying sequence.

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!