Can range based for loop work over a range
c++, c++11, foreach
Solution
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<typename It> struct range {
It begin_, end_;
It begin() const { return begin_; }
It end() const { return end_; }
};
template<typename It> range<It> as_range(const std::pair<It, It> &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.
Problem
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: ``` auto rng = std::equal_range(v.begin(),v.end(),1984); for(const auto& elem: rng) { // ... } ```