Iterators in C++ (stl) vs Java, is there a conceptual difference?

前端 未结 9 981
夕颜
夕颜 2020-12-13 09:30

I\'m returning to c++ after being away for a bit and trying to dust off the old melon.

In Java Iterator is an interface to a container having methods: hasNext

9条回答
  •  情歌与酒
    2020-12-13 09:46

    Perhaps a bit more theoretical. Mathematically, collections in C++ can be described as a half-open interval of iterators, namely one iterator pointing to the start of the collection and one iterator pointing just behind the last element.

    This convention opens up a host of possibilities. The way algorithms work in C++, they can all be applied to subsequences of a larger collection. To make such a thing work in Java, you have to create a wrapper around an existing collection that returns a different iterator.

    Another important aspect of iterators has already been mentioned by Frank. There are different concepts of iterators. Java iterators correspond to C++' input iterators, i.e. they are read-only iterators that can only be incremented one step at a time and can't go backwards.

    On the other extreme, you have C pointers which correspond exactly to C++' concept of a random access iterator.

    All in all, C++ offers a much richer and purer concept that can be applied to a much wider variety of tasks than either C pointers or Java iterators.

提交回复
热议问题