Hacker News new | ask | show | jobs
by ThatOtherPerson 4324 days ago
It's an improvement in the sense that it's more general; you can loop through any container that implements that protocol, which most (if not all) of the STL containers do. For example,

    template <class T>
    void foo(T arr)
    {
        for (auto it = arr.begin(); it != arr.end(); ++it)
        {
            std::cout << *it << std::endl;
        }
    }
You could pass a `std::map<int>` to `foo`, or a `std::list<string>`, or a `std::vector<char>`. You could even create your own classes and give them to `foo`, as long as they implement the `begin`/`end` protocol.

It's certainly more verbose than necessary, but it can be convenient.

3 comments

You want to use 'T const&' as your argument type, not 'T', otherwise foo() will take a copy of anything you pass.
I've never understood the STL's infatuation with iterators. Why do I even need to know about them when all I want is walk through the collection?

Ideally, it should be something like:

    for (auto it : arr) {
      // do something with *it
    }
You can do that. That's part of C++11 and is supported by basically every major compiler.

The advantage of iterators is that they're incredibly flexible. You can use them for sub-ranges, reversed ranges, non-ranges like input and output iterators, etc, etc. This is vastly more powerful than something like, say, Objective C's NSFastEnumeration, which just allows for the trivial case handled by the range-based for-loop.

> Why do I even need to know about them when all I want is walk through the collection?

Because there are algorithms where you may not want to walk through the whole collection. STL wasn't meant to be a container library alone, it also includes many generic algorithms that work using iterators to delimit the range of data to be operated upon.

It basically is this easy these days, thankfully. It is nice to have iterators, though, because it allows you some flexibility for swapping out the underlying data structures on existing algorithmic code. This has proved quite useful when I've written graph code.
Oh yes, and I'm hella thankful for those containers. I just wish "auto" had come along a little sooner :)