#include <iostream>
#include <iterator>
#include <algorithm>
class MyArray
{
public:
//演示自定义迭代器
struct Iterator
{
/*
第一步: 需要实现以下几种属性,这些属性是C++实现迭代器的约定,
确保STL库算法可以使用该自定义迭代器
*/
//指定迭代器类型,总共有六种input iterator, output iterator, forward iterator, bidirectional iterator, random access iterator, contigous iterator
using iterator_category = std::forward_iterator_tag;
//指定迭代器步长,本例子迭代器是对指针包装,所以步长是std::ptrdiff_t类型
using difference_type = std::ptrdiff_t;
//指定迭代器指向的元素类型,本例子是int型
using value_type = int;
//指定迭代器的指针类型,本例子是int*
using pointer = int*;
//指定迭代器的引用类型,本例子是int&
using reference = int&;
/*属性定义完毕*/
/*第二步: 定义迭代器其构造函数,指定该迭代器接受哪种容器类型,本例子是int数组,即int*指针*/
Iterator(pointer ptr):m_ptr(ptr){}
/*第三步: 实现*, ->, ++, ==, != 操作运算符*/
reference operator*() const { return *m_ptr; }
pointer operator->() { return m_ptr; }
Iterator& operator++() { m_ptr++; return *this; }
Iterator operator++(int) { Iterator tmp = *this; ++(*this); return tmp; }
friend bool operator == (const Iterator& a, const Iterator& b) { return a.m_ptr == b.m_ptr; }
friend bool operator != (const Iterator& a, const Iterator& b) { return a.m_ptr != b.m_ptr; }
/*操作运算符定义完毕*/
private:
pointer m_ptr;
};
//在容器中使用迭代器,定义begin(), end()
Iterator begin() { return Iterator(&m_data[0]); }
Iterator end() { return Iterator(&m_data[200]); }
private:
int m_data[200];
};
int main() {
MyArray arr;
//for (auto it = arr.begin(), end = arr.end(); it != end; ++it)
//{
// *it = std::distance(arr.begin(), it);
//}
std::fill(arr.begin(), arr.end(), 3);
for (auto a : arr)
{
std::cout << a << " ";
}
std::cout << std::endl;
return 0;
}
C++ STL Custom Iterator 自定义迭代器
于 2024-06-27 23:04:38 首次发布