2

The basic iterator model of C++'s STL basically consists of a "give me the item at the current position" operator *, a "go to next item" operator ++ and an a predicate ==/!= that is used to check (most of the time) against an end iterator. Of course, there are various further iterators with random access but the most basic one looks like described above.

In contrast, Java has next() and hasNext(). Next is roughly equivalent to using ++ and then *. hasNext() is something like comparison against end. Why has Java not adopted the C++ model (of course, it doesn't have operator overloading so it must mimic it by functions)? Especially, why was comparison against an end iterator dropped for a hasNext() method? I find it often harder to write iterators in Java than in C++ because the logic behind next() and hasNext() is often more complex than the one in the C++ operators.

4

3 回答 3

5

首先,您必须了解 C++ 具有指针,而迭代器模拟指针。

Java没有指针,Java中的一切都是对象

C++ 插入器功能更强大。

请参阅上述评论中的重复答案。

C ++(stl)与Java中的迭代器,有概念上的区别吗?

Java 和 C++ 中的迭代器有什么区别?

我建议您阅读 Java 中如何处理对象 - Java 中的对象

于 2013-05-27T15:32:20.103 回答
0

也许您应该将 C++ 迭代器与具有索引访问的 Java ListIterator进行比较。Java 的 Iterator 适用于所有类型的集合,并避免使用 O(n) 访问可能出现的低效索引访问。那是一个选择。当然,可以在子列表上进行迭代,获得大致相同的结果。

  • 在 Java 7 中,迭代器已经具有第二公民身份,因为有for (item : collection).
  • 在 Java 8collection.forEach(function)中提供。

Java 8forEach是一个明确的改进:来自外部的迭代器维护一个状态。forEach由集合类本身完成。这会对表现力(流畅的组合)、效率、并发性和优化产生影响。(可以在别处阅读。)

于 2013-05-27T15:45:51.410 回答
0

原谅我的英语

1、java风格的迭代器就像c++的前向迭代器类,即c++迭代器的一部分

2,在c++中,迭代器只是STL的一部分,在c++中定义一个新的迭代器不仅意味着可以遍历数据集,还意味着可以使用整个STL的能力,非常强大;</p>

于 2013-05-27T15:54:46.447 回答