2

To my understanding, iterators are a mechanism for providing an interface for the client to observe/iterate/pass through the contents of, for example, a custom collection, without breaking the information hiding principle. STL containers have iterators of their own, so we can use for ( : ) and for_each loops on them with no problems.

My question initially was: why inherit from std::iterator? What additional functionality does it provide, in contrast to the following example:

SimpleArray.h

class SimpleArray
{
    int *arr;
    int n;
public:
    explicit SimpleArray(int = 1);
    ~SimpleArray();

    friend ostream& operator<<(ostream&, const SimpleArray&);
    friend istream& operator>>(istream&, SimpleArray&);

    // encapsulated "iterator"
    class Observer
    {
        int *p;
    public:
        Observer(int *value = nullptr) : p(value) {}
        Observer& operator++() { p++; return *this; }
        Observer operator++(int) { int *temp = p; p++; return Observer(temp); }
        bool operator==(Observer other) const { return p == other.p; }
        bool operator!=(Observer other) const { return p != other.p; }
        int& operator*() const { return *p; }
    };

    Observer begin() { return Observer(arr); }
    Observer end() { return Observer(arr + n - 1); }
};

Source.cpp

int main()
{
    SimpleArray array(5);
    cin >> array;

    for (int item : array)
    {
        cout << item << " ";
    }

    cin.ignore();
    cin.get();
}

Input

1 2 3 4 5

begin() and end() functions are public and the Observer encapsulates all the necessary operators for the loop to function. The code compiled.

Output

1 2 3 4 5

After trying the same with std::for_each

std::for_each(array.begin(), array.end(), [](int item) { cout << item << " "; });

I got some compiler errors:

C2062: type 'unknown-type' unexpected   Observer
C2938: '_Iter_cat_t<SimpleArray::Observer>' : Failed to specialize alias template
C2794: 'iterator_category': is not a member of any direct or indirect base class of 'std::iterator_traits<_InIt>'

After reading about for_each, I found out its type parameters must meet some requirements, in short - to be Iterators.

My question now is: why is this function (and many others for certain) designed in a way that enforces this criteria, if it is fairly easy to create a regular class that provides the iterating functionality?

9
  • 5
    You don't have to inherit from std::iterator. In fact it has been deprecated and should not be used.
    – nwp
    Jan 25, 2018 at 14:46
  • Also your Observer does not have all the features that a proper iterator must have. Inheriting from std::iterator gave you some of them, but it turned out too confusing and you should just do it by hand.
    – nwp
    Jan 25, 2018 at 14:48
  • See std::iterator_traits en.cppreference.com/w/cpp/iterator/iterator_traits Jan 25, 2018 at 14:53
  • It's a convenience. If you prefer to write out the required typedefs yourself, go for it. Jan 25, 2018 at 16:48
  • 1
    @PeteBecker The OP is considering writing a new iterator class for which I would say you should not use deprecated features. In your scenario you remove features from working code. Totally different scenario.
    – nwp
    Jan 25, 2018 at 17:01

2 Answers 2

9

The only thing std::iterator provides are the member types iterator_category, value_type, difference_type, pointer, and reference, which are defined from the template parameters you provide. It doesn't have any other members. You can just define these member types yourself.

The real answer is that you don't need to inherit from std::iterator at all and it doesn't give you any real advantage. As far as C++ is concerned, if it looks like an iterator, it is an iterator. You just need to make sure your iterator type follows the concepts outlined here: https://en.cppreference.com/w/cpp/named_req/Iterator

std::iterator was deprecated in C++17 because of how relatively useless it is.

1
  • 3
    "if it looks like an iterator, it is an iterator" or also known as duck typing
    – Passer By
    Jan 25, 2018 at 15:44
0

Since You have an iterator in mind -in your case Observer- check out what’s required for the Iterator type you chose Observer to be (InputIterator, OutputIterator, ForwardIterator, BidirectionalIterator, RandomAccessIterator, or even ContiguousIterator) and put the requirements in place. Boom you have yourself an iterator. This is possible because of sweet old “iterator traits”.

In your scenario or any other person who might be facing the same issue, check what type of iterator you actually need -in your case, std::for_each() needs an InputIterator so as long as Observer has the traits of an InputIterator, it is an InputIterator and can be used with std::for_each().

See the Iterator Library at cpp reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.