Skip to content

Instantly share code, notes, and snippets.

@mshafae
Last active October 24, 2025 00:03
Show Gist options
  • Select an option

  • Save mshafae/89f713310ded44cb69295e94c271b7fa to your computer and use it in GitHub Desktop.

Select an option

Save mshafae/89f713310ded44cb69295e94c271b7fa to your computer and use it in GitHub Desktop.
Example of how to get to the iterator of the vector in a class
// Gist https://gist.github.com/mshafae/89f713310ded44cb69295e94c271b7fa
// Filename fast_for_loop.cc
// CompileCommand clang++ -std=c++20 fast_for_loop.cc
// Example of how to get to the iterator of the vector in a class
#include <iostream>
#include <iterator>
#include <vector>
class Wrapper {
public:
std::vector<int>::const_iterator begin() const { return n.begin();}
std::vector<int>::const_iterator end() const { return n.end(); }
private:
std::vector<int> n{10, 11, 12, 13, 14, 15};
};
// From https://www.digitalocean.com/community/tutorials/foreach-loop-c-plus-plus
class NumberRange {
private:
int startv;
int endv;
// Iterator implementation
class Iterator {
private:
int current;
public:
Iterator(int value) : current(value) {}
int operator*() const { return current; }
Iterator& operator++() {
++current;
return *this;
}
bool operator!=(const Iterator& other) const {
return current != other.current;
}
};
public:
NumberRange(int start, int end) : startv(start), endv(end) {}
Iterator begin() const { return Iterator(startv); }
Iterator end() const { return Iterator(endv); }
};
int main(int argc, char const* argv[]) {
for (int i : NumberRange(1, 6)) {
std::cout << i << " "; // Outputs: 1 2 3 4 5
}
Wrapper p;
for (const auto& x : p) {
std::cout << x << "\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment