I wrote an OutputIterator for an answer to another question. Here it is:
#include
using namespace std;
template< typename T, typename U &g
#include
#include
#include
#include
using namespace std;
template< typename T, typename U >
class queue_inserter
{
queue &qu;
public:
// for iterator_traits to refer
typedef output_iterator_tag iterator_category;
typedef T value_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef T& reference;
queue_inserter(queue &q) : qu(q) { }
queue_inserter& operator ++ () { return *this; }
queue_inserter operator * () { return *this; }
void operator = (const T &val) { qu.push(val); }
};
template< typename T, typename U >
queue_inserter make_queue_inserter(queue &q)
{
return queue_inserter(q);
}
int main()
{
// uses initalizer list (C++0x), pass -std=c++0x to g++
vector v({1, 2, 3});
queue> q;
copy(v.cbegin(), v.cend(), make_queue_inserter(q));
while (!q.empty())
{
cout << q.front() << endl;
q.pop();
}
}
This should do it with iterator_traits; a helper struct in which defines all types an iterator should typically define. Functions in , refer to these types when required like iterator_traits or say iterator_traits, etc. Just defining them inside one's custom iterator would do the trick. This is the modern way of writing iterators, as opposed to the classical way of inheriting from std::iterator. Having a look at reveals that even std::iterator defines these types i.e. iterator_category, difference_type, etc. This is the reason, when inherited from std::iterator, the derived iterator class gets these due to heredity.