Comparing Iterators from Different Containers: A Cautionary Tale
In C++, iterators provide a powerful mechanism for traversing collections. However, it is important to be aware of the limitations when using iterators from different containers.
The question of whether it is legal to compare iterators from different containers arises frequently. Consider the following example:
std::vector<int> foo;
std::vector<int> bar;
std::cout << (foo.begin() == bar.begin());
This expression may seem harmless at first glance, but it actually yields undefined behavior. According to the C++11 standard, iterators can only be compared if they refer to elements of the same sequence. Since foo and bar are two distinct vectors, their iterators are not comparable.
This behavior is further emphasized in LWG issue #446:
"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."
This restriction has significant implications for implementing custom iterators. If you plan to implement an operator== for your custom iterator, you must ensure that it only compares iterators that are within the same range.
Failing to adhere to this rule can lead to unexpected behavior and is ultimately detrimental to the reliability of your code. Therefore, it is crucial to keep in mind that comparing iterators from different containers is strictly prohibited in C++.
Clause de non-responsabilité: Toutes les ressources fournies proviennent en partie d'Internet. En cas de violation de vos droits d'auteur ou d'autres droits et intérêts, veuillez expliquer les raisons détaillées et fournir une preuve du droit d'auteur ou des droits et intérêts, puis l'envoyer à l'adresse e-mail : [email protected]. Nous nous en occuperons pour vous dans les plus brefs délais.
Copyright© 2022 湘ICP备2022001581号-3