C++ 14制作自定义迭代器,它将经过2并返回修改后的数据

标签 c++ iterator c++14

我有课Range它拥有一个像<2,10>这样的区间或 <-50,900> 比我有 RangeList我想要 vector<long long>代表多个范围。我不需要 vector<Range>出于某种目的。

但我想制作一个迭代器,它将通过 ranges它将重新运行 Range。是否可以定义像那样工作的自定义迭代器?

   class Range {
        long long lo;
        long long hi;
    }

    class RangeList {
    vector<long long> ranges;

    }

例子

ranges={1, 50, 200, 700, 900, 1000};

所以迭代器会遍历并返回

第一次迭代

Range <1,50>

二选一

Range <200,700>

第三次

Range <900,100>

感谢任何建议

最佳答案

我想我会更具体一点,因为我不喜欢从连续的值列表中推断成对(如果值的数量是奇数会怎样?)

#include <vector>
#include <iostream>

template<class Integer>
struct InclusiveRangeIter
{
    using iterator_category = std::forward_iterator_tag;
    using value_type = Integer;
    using reference = value_type&;
    using pointer = value_type*;
    using difference_type = Integer;

    constexpr InclusiveRangeIter(Integer current)
    : value_(current)
    {}

    constexpr bool operator==(InclusiveRangeIter const& other) const { return value_ == other.value_; }
    constexpr bool operator!=(InclusiveRangeIter const& other) const { return value_ != other.value_; }
    value_type operator*() const { return value_; }
    auto operator++() -> InclusiveRangeIter& { ++value_; return *this; }
    auto operator++(int) -> InclusiveRangeIter { auto copy = *this; ++value_; return copy; }


    Integer value_;
};

struct InclusiveRange 
{
    long long lo;
    long long hi;

    auto begin() const { return InclusiveRangeIter(lo); }
    auto end() const { return InclusiveRangeIter(hi + 1); }
};

int main()
{
    auto ranges = std::vector<InclusiveRange>
    {
        {1, 50}, {200, 700}, {900, 1000}
    };

    for (auto&& ir : ranges)
    {
        auto sep = false;
        for (auto&& v : ir)
        {
            if (sep) std::cout << ", ";
            std::cout << v;
            sep = true;
        }
        std::cout << '\n';
    }
}

https://coliru.stacked-crooked.com/a/2804de3d85ba4f0b

关于C++ 14制作自定义迭代器,它将经过2并返回修改后的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55335219/

相关文章:

c++ - boost::filesystem::path::native() 返回 std::basic_string<wchar_t> 而不是 std::basic_string<char>

algorithm - 是否可以仅使用迭代器输出 1,...,n 的排列?

c++ - 标记 union C++

c++ - 在不公开变量模板的情况下在内联 constexpr 函数中使用变量模板?

c++ - 如何构造不可移动不可复制对象的元组?

c++ - For 循环退出条件(size_t 与 int)

c++ - Netbeans C/C++ 多文件编译

c++ - typeid(T) 是在运行时还是编译时求值?

C++,如何从迭代器返回对成员变量的引用

python - 如何将可迭代对象转换为流?