C++11—迭代器类实现
来源:互联网 发布:程序员联合网 编辑:程序博客网 时间:2024/06/14 00:37
//迭代器类namespace detail_range{template <typename T>class iterator{public:using value_type = T;using size_type = size_t;private:size_type cursor_;const value_type step_;value_type value_;public:iterator(size_type cur_start, value_type begin_val, value_type step_val):cursor_(cur_start), step_(step_val), value_(begin_val){value_ += (step_*cursor_);}value_type operator*()const{return value_;}bool operator!=(const iterator&rhs)const{return (cursor_ != rhs.cursor_);}iterator& operator++(void){value_ += step_;++cursor_;return (*this);}};template<typename T>class impl{public:using value_type = T;using reference = const value_type&;using const_reference = const value_type&;using iterator = const detail_range::iterator<value_type>;using const_iterator = const detail_range::iterator<value_type>;using size_type = typename iterator::size_type;private:const value_type begin_;const value_type end_;const value_type step_;const size_type max_count_;size_type get_adjusted_count(void) const{if (step_ > 0 && begin_ >= end_){throw std::logic_error("End value must be greater than begin value.");}else if (step_<0 && begin_<end_){throw std::logic_error("End value must be less than begin value.");}size_type x = static_cast<size_type>((end_ - begin_) / step_);if (begin_ + (step_*x) != end_){++x;}return x;}public:impl(value_type begin_value, value_type end_val, value_type step_val):begin_(begin_value), end_(end_val), step_(step_val), max_count_(get_adjusted_count()){}size_type size(void) const{return max_count_;}const_iterator begin(void) const{return{ 0, begin_, step_ };}const_iterator end(void) const{return{ max_count_, begin_, step_ };}};template <typename T>detail_range::impl<T> range(T end){return{ {}, end, 1 };}template<typename T>detail_range::impl<T> range(T begin, T end){return{ begin, end, 1 };}template <typename T, typename U>auto range(T begin, T end, U step)->detail_range::impl<decltype(T + U)>{using r_t = detail_range::impl<decltype(begin + end)>;return r_t(begin, end, step);}void test_range(void){std::cout << "range(15): ";for (int i : range(15)){std::cout << " " << i;}std::cout << std::endl;}}//namespace detail_rangeint main(){detail_range::test_range();return 0;}
其中test_range为测试函数
0 0
- C/C++——strcmp函数实现
- C/C++——strcmp函数实现
- C库函数—strcpy实现
- C库函数—strcpy实现
- C/C++: 实现加减乘除。
- C实现C(3)
- C/C++——strcpy函数的实现
- C或C++——strcpy函数的实现
- C/C++——strcpy函数的实现和解析
- C/C++——strcpy函数的实现
- C/C++——strcpy函数的实现 和解析
- 【C语言】简易扫雷游戏——C语言实现
- 11 C语言实现约瑟夫问题
- Vector 的简单实现 C++11
- RTree源代码——C语言实现
- C语言实现系列——队列
- 常用排序算法——C实现
- 堆排序——ANSI C实现
- Android 获取当前activity的屏幕截图
- 更改CMD默认的初始路径
- spring4学习记录02-spring AOP
- C语言 const 用法
- js控制文字一个一个的显示出来
- C++11—迭代器类实现
- 【矩阵快速幂】 hdu5667 Sequence 、nyoj1000 又见斐波那契数列
- spring boot整合security
- [积跬成千]wpf基础之Visibility与Opacity的区别
- LeetCode (17)Letter Combinations of a Phone Number
- C语言中static用法
- 数字图像处理]常见噪声的分类与Matlab实现
- fileURLWithPath与 URLWithString的区别
- 想要提高网站的访问量 就先要仔细分析网站的kpi