c++ - How to compare (the order) of two bidirectional iterators? -
i wondering if there build-in way in c++ compare order of 2 bidirectional iterators. example, have sum function calculate sum between 2 iterators in same list:
double sum(std::list::const_iterator start, std::list::const_iterator end){ double sum=0; (start;start!=end;start++) sum+=*start; return sum; }
then: sum(my_list.begin(),my_list.end());
fine, sum(my_list.end(),my_list.begin());
cause runtime error.
i thinking puttingif (start>end) return 0;
prevent error. seems cannot compare iterators this.
you should read introduction stl explains various refinements of iterator concept.
only randomaccessiterators support comparison <
because not efficient operation non-randomaccessiterators.
the way tell if bidirectionaliterator i
less-than another, j
, incrementing i
1 step @ time , seeing if ever reach j
, never happen if j
not reachable i
, , error if i
not incrementable, e.g. because past-the-end iterator range.
alternatively, decrement i
, see if reach j
, in case know j
less-than i
, won't work if i
begin iterator, because can't iterate before beginning of range.
so in general there no way know whether 1 non-randomaccessiterator comes before or after another, because can't know whether start iterating forwards or backwards reach other, , wouldn't know when safe keep going or when reach end of valid range.
so convention pass iterators in same order, begin iterator comes first, , past-the-end iterator comes second, , past-the-end iterator can reached incrementing begin iterator 0 or more times.
then:
sum(my_list.begin(),my_list.end());
fine,sum(my_list.end(),my_list.begin());
cause runtime error.
don't then!
it caller's responsibility call function correctly, , why caller not know iterator start , end?
Comments
Post a Comment