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++.
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3