Can range based for loop work over a range

前端 未结 4 1031
醉梦人生
醉梦人生 2021-01-04 21:04

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:



        
4条回答
  •  被撕碎了的回忆
    2021-01-04 21:39

    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.

提交回复
热议问题