If I have range (pair of 2 iterators) is there a way to write \"for each\" loop for that uses range, not a raw array or container.
Something like this:
As per Why was pair range access removed from C++11? you can use an adaptor e.g. the as_range
at the accepted answer, boost::make_iterator_range, or write your own:
template struct range {
It begin_, end_;
It begin() const { return begin_; }
It end() const { return end_; }
};
template range as_range(const std::pair &p) {
return {p.first, p.second};
}
auto rng = std::equal_range(v.begin(),v.end(),1984);
for(const auto& elem: as_range(rng))
...
The reason this isn't applicable in general is that per Alastair Meredith's paper, of the algorithms,
mismatch
and partition_copy
return a pair of iterators from different ranges;minmax
returns a pair of objects that may not be iterators at all, and if they are there's no guarantee they form a range;minmax_element
can return a range, but it can also return a reversed range (e.g. on a reverse-sorted range minmax_element
will return {prev(last), first}
;equal_range
is guaranteed to return a range.