Skip to content

Commit f377ad9

Browse files
committed
iterator: add position iterator to count the increment value
1 parent 85acec0 commit f377ad9

File tree

1 file changed

+64
-1
lines changed

1 file changed

+64
-1
lines changed

include/chen/base/iterator.hpp

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,7 @@ namespace chen
446446
};
447447

448448
/**
449-
* Handy type alias(C++11)
449+
* Type alias(C++11)
450450
*/
451451
template<typename Value, typename Reference = Value&, typename Pointer = Value*, typename Distance = std::ptrdiff_t>
452452
using input_iterator = iterator<std::input_iterator_tag, Value, Reference, Pointer, Distance>;
@@ -459,4 +459,67 @@ namespace chen
459459

460460
template<typename Value, typename Reference = Value&, typename Pointer = Value*, typename Distance = std::ptrdiff_t>
461461
using random_iterator = iterator<std::random_access_iterator_tag, Value, Reference, Pointer, Distance>;
462+
463+
/**
464+
* Position iterator
465+
* since input iterator is single-pass, we can't use std::distance on it
466+
* however, in some cases we want to know input iterator's position, so I add this iterator
467+
*/
468+
template <typename Value, typename Reference = Value&, typename Pointer = Value*, typename Distance = std::ptrdiff_t>
469+
class position_iterator : public input_iterator<Value, Reference, Pointer, Distance>
470+
{
471+
public:
472+
typedef input_iterator<Value, Reference, Pointer, Distance> super_class;
473+
474+
using typename super_class::value_type;
475+
using typename super_class::difference_type;
476+
using typename super_class::pointer;
477+
using typename super_class::reference;
478+
using typename super_class::iterator_category;
479+
using typename super_class::data_type;
480+
481+
public:
482+
/**
483+
* Construct by proxy
484+
*/
485+
position_iterator(const iterator_helper::proxy<Value, data_type> &p) : super_class(p)
486+
{
487+
}
488+
489+
/**
490+
* Wrap another iterator
491+
*/
492+
template <typename Iterator>
493+
position_iterator(Iterator it) : super_class(it)
494+
{
495+
}
496+
497+
public:
498+
/**
499+
* Current position after increment
500+
*/
501+
Distance distance() const
502+
{
503+
return this->_distance;
504+
}
505+
506+
public:
507+
/**
508+
* Input & Forward iterator
509+
*/
510+
super_class& operator++()
511+
{
512+
++this->_distance;
513+
return super_class::operator++();
514+
}
515+
516+
iterator_helper::proxy<Value, data_type> operator++(int)
517+
{
518+
++this->_distance; // don't effect on proxy
519+
return super_class::operator++(0);
520+
}
521+
522+
private:
523+
Distance _distance = 0;
524+
};
462525
}

0 commit comments

Comments
 (0)