Skip to content

Instantly share code, notes, and snippets.

@xzhong86
Last active April 18, 2024 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xzhong86/3b54fe09583dec3055c81d6fc056c0f4 to your computer and use it in GitHub Desktop.
Save xzhong86/3b54fe09583dec3055c81d6fc056c0f4 to your computer and use it in GitHub Desktop.
C++ range-based for statement
#include <iostream>
class Range {
int start, end_;
int step;
public:
Range(int end) : start(0), end_(end), step(1) { }
Range(int b, int e, int s) : start(b), end_(e), step(s) { }
class Iterator {
int cur;
int step;
public:
Iterator(int c, int s) : cur(c), step(s) { }
// API for range-based for statement
bool operator !=(const Iterator& rhs) const { return cur != rhs.cur; }
Iterator& operator ++() { cur += step; return *this; }
int operator *() { return cur; }
};
Iterator begin() const { return Iterator(start, step); }
Iterator end() const { return Iterator(end_, 0); }
Range reverse() const { return Range(end_ - step, start - step, 0 - step); }
};
int main() {
#define PRINT_RANGE(R) \
std::cout << #R " = "; \
for (auto i: R) std::cout << i << " "; \
std::cout << std::endl;
PRINT_RANGE(Range(5));
PRINT_RANGE(Range(2, 10, 2));
PRINT_RANGE(Range(10, 0, -2));
PRINT_RANGE(Range(5).reverse());
}
// g++ -O2 range-based-for.cpp && ./a.out

C++ Simple Range

A simple Range class for int with c++ range-based for statement supported. (or c++ foreach statement) (aka. minimal code to support c++ foreach/range-based-for)

As we know from this example, to support range-based for we need:

  1. container/custom-class has begin() end() method, which return a iterator or something else.
  2. iterator has implemented operators:
  3. not-equal operator !=, which is bool operator !=(T&)
  4. pre-increment operator ++, which is T operator ++()
  5. indirection operator *, which is T operator *()

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment