Last active
August 29, 2015 14:01
-
-
Save Giemsa/18c08646bb315746ba84 to your computer and use it in GitHub Desktop.
イテレーションしつつインデックスるも取るコード
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
#include <iostream> | |
#include <vector> | |
/* -- ここから -- */ | |
template<typename T, typename C = int> | |
class Element | |
{ | |
template<typename S> | |
friend class Iterator; | |
private: | |
inline void set(const C i, T &v) | |
{ | |
index = i; | |
value = v; | |
} | |
public: | |
C index; | |
T &value; | |
inline Element(const C idx, T &val) : index(idx), value(val) { } | |
}; | |
template<typename T> | |
class Iterator | |
{ | |
typedef typename T::iterator iter_type; | |
typedef Element<typename T::value_type> elem_type; | |
private: | |
int index; | |
iter_type iterator; | |
elem_type elem; | |
public: | |
inline Iterator(iter_type it) : index(0), iterator(it), elem(0, *it) { } | |
inline bool operator!=(const Iterator<T> &it) const { return iterator != it.iterator; } | |
inline elem_type &operator*() { return elem; } | |
inline elem_type *operator->() { return &(operator*());} | |
inline const Iterator &operator++() | |
{ | |
elem.set(++index, *(++iterator)); | |
return *this; | |
} | |
}; | |
template<typename T> | |
class WithIndex | |
{ | |
public: | |
typedef Iterator<T> iterator; | |
private: | |
T &iterable; | |
public: | |
inline WithIndex(T &iterable) : iterable(iterable) { } | |
inline Iterator<T> begin() const { return Iterator<T>(iterable.begin()); } | |
inline Iterator<T> end() const { return Iterator<T>(iterable.end()); } | |
}; | |
template<typename T> | |
inline WithIndex<T> withIndex(T &iterable) { return WithIndex<T>(iterable); } | |
/* -- ここまで -- */ | |
int main(int argc, const char * argv[]) | |
{ | |
std::vector<int> iv = { 2, 4, 6, 8, 10 }; | |
for(auto &e : withIndex(iv)) // インデックスも取る! | |
{ | |
std::cout << e.index << ": " << e.value << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment