Created
January 1, 2023 08:04
-
-
Save pebble8888/a8321917506befb35c405989589fec3c to your computer and use it in GitHub Desktop.
forward iterator sample
This file contains 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
#pragma once | |
#include <memory> | |
#include <iterator> | |
template<typename T> | |
class Primes { | |
public: | |
class prime_iterator { | |
public: | |
using iterator_category = std::forward_iterator_tag; | |
using value_type = T; | |
using difference_type = ptrdiff_t; | |
prime_iterator(T* buf, int size, int index) | |
: buf_(buf) | |
, size_(size) | |
, index_(index) | |
{ | |
} | |
T& operator*() { | |
if (buf_ && index_ >= 0 && index_ < size_) { | |
return buf_[index_]; | |
} | |
return zero_; | |
} | |
bool operator==(const prime_iterator& other) const { | |
return buf_ == other.buf_ && | |
size_ == other.size_ && | |
index_ == other.index_; | |
} | |
bool operator!=(const prime_iterator& other) const { | |
return !(*this == other); | |
} | |
prime_iterator& operator++() { | |
++index_; | |
return *this; | |
} | |
prime_iterator operator++(int) { | |
auto copy = *this; | |
++index_; | |
return copy; | |
} | |
private: | |
T* buf_; | |
int size_; | |
int index_; | |
T zero_ {}; | |
}; | |
std::unique_ptr<T[]> buf_; | |
int size_; | |
prime_iterator begin() { | |
return { buf_.get(), size_, 0 }; | |
} | |
prime_iterator end() { | |
return { buf_.get(), size_, size_ }; | |
} | |
static Primes create() { | |
Primes primes; | |
primes.size_ = 10; | |
primes.buf_ = std::make_unique<T[]>(10); | |
primes.buf_[0] = 2; | |
primes.buf_[1] = 3; | |
primes.buf_[2] = 5; | |
primes.buf_[3] = 7; | |
primes.buf_[4] = 11; | |
primes.buf_[5] = 13; | |
primes.buf_[6] = 17; | |
primes.buf_[7] = 19; | |
primes.buf_[8] = 23; | |
primes.buf_[9] = 29; | |
return primes; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment