Check if two iterators come from the same object

Given two std :: iterators of the same type, how can I check if the same object (and not the class) comes from? Notice I am not asking how to compare their meanings.

std::string foo = "foo"; std::string bar = "bar"; std::string::iterator iter1 = foo.begin(); std::string::iterator iter2 = bar.begin(); if ( iter1 == iter2 ) { ... } 

The above should and will not work. How can I check this at runtime? Looking in the source code, I see that the corresponding methods call iterator::_Compat() , this is the void method, which performs the check that I want, but if it fails, it displays a debug message. It will be imperceptible in releases.

In the future, I see that the iterator (at least for the string) has the public method _GetCont() . So

 if ( iter1._GetCont() == iter2._GetCont() ) 

works. But this is undocumented, making me believe that it is unsafe.

My question is, how can I do the above in portable mode?

It should also be noted that this is part of the iterator pattern class. I will not control the second iterator.

+4
source share
2 answers

My question is, how can I do the above in portable mode?

You can not.

In general, iterators do not need to know (or tell you) about the container they are pointing to. Iterators are a generalization of pointers, and all they have to do is behave like pointers.

Thus, they can allow dereferencing, increasing, decreasing, summing, etc., depending on their category, but in the C ++ standard there is no iterator requirement to tell their user in which container they indicate or indicate whether they are on the same container as another iterator.

In other words, the validity of the iterator range must be a prerequisite for a function that works in this iterator range. The client is responsible for ensuring that the provided iterators point to the same container (and that the second iterator is accessible from the first).

For example, here is how the standard library deals with this issue (paragraph 24.2.1 / 7 of the C ++ 11 standard):

Most algorithmic library templates that work with data structures have interfaces that use ranges. A range is a pair of iterators that indicate the beginning and end of a calculation. The range [i,i) is an empty range; in the general case, the range [i,j) refers to elements in the data structure, starting from the element indicated by i and before, but not including the element pointed to by j . The range [i,j) valid if and only if j reachable from i . The result of applying functions in the library to invalid ranges is undefined .

+6
source

You can compare pointers

 if ( &(*iter1) == &(*iter2) ) { ... } 
0
source

Source: https://habr.com/ru/post/1489928/


All Articles