Can range based for loop work over a range

前端 未结 4 1027
醉梦人生
醉梦人生 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:52

    #include 
    #include 
    #include 
    
    template 
    struct range_adapter {
        std::pair p;
    
        range_adapter(const std::pair &p) : p(p) {}
    
        I begin() const { return p.first; }
        I end() const { return p.second; }
    };
    
    template 
    range_adapter in_range(const std::pair &p)
    {
        return range_adapter(p);
    }
    
    int main()
    {
        std::vector data { 1, 2, 2, 3, 3, 3, 4 };
    
        auto r = std::equal_range(data.begin(), data.end(), 2);
    
        for (const auto &elem : in_range(r))
        {
            std::cout << elem << std::endl;
        }
    }
    

提交回复
热议问题