Hacker News new | ask | show | jobs
by zak_mc_kracken 4324 days ago
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
    }
3 comments

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.