본문 바로가기
프로그래밍 언어/C,C++

C++ range와 range iterator

by pagehit 2022. 3. 3.
반응형
#include <cstdio>

struct FibonacciIterator {
    bool operator!=(int x) const {
        return x >= current;
    }

    FibonacciIterator& operator++() {
        const auto tmp = current;
        current += last;
        last = tmp;
        return *this;
    }

    int operator*() const {
        return current;
    }
private:
    int current{1}, last{1};
};

struct FibonacciRange {
    explicit FibonacciRange(int max) : max{ max } { }
    FibonacciIterator begin() const {
        return FibonacciIterator{};
    }
    int end() const {
        return max;
    }
private:
    const int max;
};

int main() {
    for (const auto i : FibonacciRange{ 50 }) {
        printf("%d ", i);
    }

    // FibonacciRange range{ 50 };
    // const auto end = range.end();
    // for (const auto x = range.begin(); x != end; ++x) {
    //     const auto i = *x;
    //     printf("%d ", i);
    // }
    return 0;
}

 

You might be thinking, “Sure, the range-based for loop looks a lot cleaner, but implementing FibonacciIterator and FibonacciRange is a lot of work.” That’s a great point, and for one-time-use code, you probably wouldn’t refactor code in this way. Ranges are mainly useful if you’re writing library code, writing code that you’ll reuse often, or simply consuming ranges that someone else has written.

반응형

댓글