Last active
August 29, 2015 14:12
-
-
Save kolodziej/004ab05235b09d77def4 to your computer and use it in GitHub Desktop.
cyclic_iterator.hpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* CyclicIterator | |
* Cyclic iterator for STL containers. | |
* @author Kacper Kołodziej | |
* @url http://kacperkolodziej.com/ | |
* @email kacper@kolodziej.in | |
*/ | |
#ifndef CYCLIC_ITERATOR_HPP | |
#define CYCLIC_ITERATOR_HPP | |
#include <iterator> | |
template <typename Container> | |
using ContainerValueType = typename Container::value_type; | |
template <typename Container> | |
using ContainerIterator = typename Container::iterator; | |
template <typename Container, typename T = ContainerValueType<Container>, typename Iterator = ContainerIterator<Container>> | |
class CyclicIterator : | |
public std::iterator<std::bidirectional_iterator_tag, T, std::ptrdiff_t> | |
{ | |
private: | |
Container& container_; | |
Iterator cursor_; | |
public: | |
CyclicIterator(Container& c) : | |
container_(c), | |
cursor_(c.begin()) | |
{} | |
bool operator==(const CyclicIterator& it) | |
{ | |
return cursor_ == it.cursor_; | |
} | |
bool operator!=(const CyclicIterator& it) | |
{ | |
return !(cursor_ == it.cursor_); | |
} | |
T& operator*() | |
{ | |
return *cursor_; | |
} | |
CyclicIterator& operator++() | |
{ | |
++cursor_; | |
if (cursor_ == container_.end()) | |
{ | |
cursor_ = container_.begin(); | |
} | |
return *this; | |
} | |
CyclicIterator operator++(int) | |
{ | |
CyclicIterator it = *this; | |
++(*this); | |
return it; | |
} | |
CyclicIterator& operator--() | |
{ | |
if (cursor_ == container_.begin()) | |
{ | |
cursor_ = container_.end(); | |
} | |
--cursor_; | |
return *this; | |
} | |
CyclicIterator operator--(int) | |
{ | |
CyclicIterator it = *this; | |
--(*this); | |
return it; | |
} | |
}; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment