即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

C++11—迭代器类实现

编程语言 J_Anson 18℃ 0评论

//迭代器类
namespace detail_range
{
 template 
 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
 class impl
 {
 public:
  using value_type = T;
  using reference = const value_type&;
  using const_reference = const value_type&;
  using iterator = const detail_range::iterator;
  using const_iterator = const detail_range::iterator;
  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_ - 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 
 detail_range::impl range(T end)
 {
  return{ {}, end, 1 };
 }
 template
 detail_range::impl range(T begin, T end)
 {
  return{ begin, end, 1 };
 }
 template 
 auto range(T begin, T end, U step)->detail_range::impl
 {
  using r_t = detail_range::impl;
  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_range
int main()
{
 detail_range::test_range();
 return 0;
}



其中test_range为测试函数








转载请注明:CodingBlog » C++11—迭代器类实现

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情