Last active
September 20, 2022 17:34
-
-
Save mjschutz/fc45bc303f3a3711c388 to your computer and use it in GitHub Desktop.
Example implementation of std::iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iterator> // std::iterator,std::input_iterator_tag | |
#include <iostream> // std::cout | |
template <typename T, size_t N> | |
class SampleVector | |
{ | |
T vector[N]; | |
public: | |
class iterator : public std::iterator<std::input_iterator_tag, T> | |
{ | |
T* vector_ptr; | |
public: | |
iterator(T* vector) : vector_ptr(vector) {} | |
iterator& operator++() { ++vector_ptr; return *this;} | |
iterator operator++(int) { iterator tmp(*this); operator++(); return tmp; } | |
bool operator==(const iterator& rhs) { return vector_ptr == rhs.vector_ptr; } | |
bool operator!=(const iterator& rhs) { return vector_ptr != rhs.vector_ptr; } | |
int& operator*() {return *vector_ptr;} | |
}; | |
SampleVector() {} | |
template <typename... Tp> | |
SampleVector(Tp... vec): vector{vec...} {} | |
iterator begin() | |
{ | |
return iterator(vector); | |
} | |
iterator end() | |
{ | |
return iterator(vector+N); | |
} | |
}; | |
SampleVector<int, 5> vector(80, 40, 30, 45, 50); | |
int main() | |
{ | |
for (int value: vector) | |
std::cout << value << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment