Re: STL algorithm adapter
Well, it may be easiest if you can convince the library author to augment the class template with iterator support. If that cannot be done, then one way out is to write your own iterator class template, e.g.,
Code:
template <typename T>
class MyCollectionIterator : public std::iterator<std::input_iterator_tag, T>
{
public:
explicit MyCollectionIterator(MyCollection<T>& collection_, unsigned long index_=0) :
collection(&collection_), index(index_) {}
const T& operator*() const
{
return (*collection)[index];
}
const T* operator->() const
{
return &(operator*());
}
MyCollectionIterator<T>& operator++()
{
++index;
return *this;
}
bool operator==(const MyCollectionIterator<T>& other) const
{
return index == other.index && collection == other.collection;
}
private:
MyCollection<T>* collection;
unsigned long index;
};
template <typename T>
MyCollectionIterator<T> operator++(MyCollectionIterator<T>& iterator, int)
{
MyCollectionIterator<T> temp(iterator);
++iterator;
return temp;
}
template <typename T>
bool operator!=(const MyCollectionIterator<T>& lhs, const MyCollectionIterator<T>& rhs)
{
return !(lhs == rhs);
}
template <typename T>
MyCollectionIterator<T> begin(MyCollection<T>& collection)
{
return MyCollectionIterator<T>(collection);
}
template <typename T>
MyCollectionIterator<T> end(MyCollection<T>& collection)
{
return MyCollectionIterator<T>(collection, collection.length());
}
// Example usage:
int main()
{
MyCollection<int> collection;
// ...
std::copy(begin(collection), end(collection),
std::ostream_iterator<int>(std::cout, "\n"));
}
Given the interface of MyCollection, you probably want a random access iterator, not an input iterator, but I simplified for this example. Furthermore, it looks as if the MyCollection class template actually is an immutable type, in which case perhaps it would be simpler to just provide a const_iterator version of the iterator instead of both versions.
Re: STL algorithm adapter
Thank you.
That looks very interesting.
Will study it in more detail the coming week.
Re: STL algorithm adapter