之前写 python 的时候我一直很喜欢的一个东西就是迭代器,用起来真的很方便,最接近开始写 cpp 觉得没有这个东西不行,研究了一下,cpp正好支持这样的特性(虽然还是冗长且不好用)。
我们先看一下 cppreference 上关于这一块说明
template<
class Category,
class T,
class Distance = std::ptrdiff_t, // (deprecated in C++17)
class Pointer = T*,
class Reference = T&
> struct iterator;
// std::iterator is the base class provided to simplify definitions of the required types for iterators.
// Template parameters
// Category - the category of the iterator. Must be one of iterator category tags.
// T - the type of the values that can be obtained by dereferencing the iterator. This type should be void for output iterators.
// Distance - a type that can be used to identify distance between iterators
// Pointer - defines a pointer to the type iterated over (T)
// Reference - defines a reference to the type iterated over (T)
// Member types下面我直接引用 cppreference 的示例代码了,对照着上面的文档还是挺好懂的。
#include <iostream>
#include <algorithm>
template <long FROM, long TO>
class Range {
public:
// member typedefs provided through inheriting from std::iterator
class iterator : public std::iterator<
std::input_iterator_tag, // iterator_category
long, // value_type
long, // difference_type
const long*, // pointer
long // reference
> {
long num = FROM;
public:
explicit iterator(long _num = 0) : num(_num) {}
iterator& operator++() {
num = TO >= FROM ? num + 1 : num - 1;
return *this;
}
iterator operator++(int) {
iterator retval = *this;
++(*this);
return retval;
}
bool operator==(iterator other) const { return num == other.num; }
bool operator!=(iterator other) const { return !(*this == other); }
reference operator*() const { return num; }
};
iterator begin() { return iterator(FROM); }
iterator end() { return iterator(TO >= FROM ? TO + 1 : TO - 1); }
};
int main() {
// std::find requires an input iterator
auto range = Range<15, 25>();
auto itr = std::find(range.begin(), range.end(), 18);
std::cout << *itr << '\n'; // 18
// Range::iterator also satisfies range-based for requirements
for (long l : Range<3, 5>()) {
std::cout << l << ' '; // 3 4 5
}
std::cout << '\n';
}