[C++]for each の続き
CountEnumerable みたいな、自分が何番目の値かを知ることが出来る iterator が欲しくなってきたので、for each で実装できるような形で作ってみました。
template<class TValue>
class loop_count_value
{
public:
TValue& value;
int count;
loop_count_value(loop_count_value& v)
: value(v.value), count(v.count) { }
loop_count_value(TValue& v, int c)]
: value(v), count(c) { }
};
template<class TIter, class TValue>
class loop_count_iterator
{
int count;
public:
TIter iter;
loop_count_iterator(TIter iter_, int count_ = 0)
: iter(iter_), count(count_) { }
loop_count_iterator& operator++()
{
++iter;
++count;
return *this;
}
bool operator!=(const loop_count_iterator& right) const
{
return (iter != right.iter);
}
loop_count_value<TValue> operator*() const
{
return loop_count_value<TValue>(*iter, count);
}
};
template<class TColl>
class loop_count_iteratable
{
private:
TColl& coll;
public:
typedef typename TColl::iterator iterator;
typedef typename TColl::value_type value_type;
loop_count_iterator<iterator, value_type> begin() const
{
return loop_count_iterator<iterator, value_type>(coll.begin());
}
loop_count_iterator<iterator, value_type> end() const
{
return loop_count_iterator<iterator, value_type>(coll.end());
}
loop_count_iteratable(TColl& coll_)
: coll(coll_) { }
};
template<class TColl>
loop_count_iteratable<TColl> loop_count(TColl& iteratable)
{
return loop_count_iteratable<TColl>(iteratable);
}
テスト
std::vector<int> v;
v.push_back(8);
v.push_back(9);
v.push_back(3);
for each (loop_count_value<int> value in loop_count(v))
{
std::cout << "[" << value.count << "] = " << value.value << std::endl;
}
実行結果
v[0] = 8
v[1] = 9
v[2] = 3
便利……なのか?