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

<p>In Java Iterator is an interface to a container having methods: <code>hasNext()</code>, <code>next()</code> and <code>remove()</code>. The presence of <code>hasNext()</code> means it <strong>has the concept of a limit</strong> for the container being traversed.</p>

<pre><code>//with an Iterator
Iterator&lt;String&gt; iter = trees.iterator();
while (iter.hasNext()) 
{
    System.out.println(iter.next());
}
</code></pre>

<p>In the C++ standard template library, iterators seem to represent a datatype or class the supports the <code>operator++</code> and <code>operator==</code> but has <strong>no concept of a limit</strong> built in so comparison is required before advancing to the next item. The limit has to checked by the user comparing two iterators in the normal case the second iterator is the container end.</p>

<pre><code>vector&lt;int&gt; vec;
vector&lt;int&gt;::iterator iter;

// Add some elements to vector
v.push_back(1);
v.push_back(4);
v.push_back(8);

for (iter= v.begin(); iter != v.end(); iter++)
{
    cout &lt;&lt; *i &lt;&lt; " "; //Should output 1 4 8
}
</code></pre>

<p>The interesting part here is that in C++ a pointer is an iterator to an array. The STL took what was existing and build convention around it.</p>

<p>It there any further subtlety to this that I am missing?</p>

[{'answer_id': 56370, 'author': 'Frank Krueger', 'author_id': 338, 'author_profile': 'https://Stackoverflow.com/users/338', 'pm_score': 5, 'selected': True, 'text': '<p>Yes, there is a large conceptual difference. C++ utilizes different "classes" of iterators. Some are used for random access (unlike Java), some are used for forward access (like java). While even others are used for writing data (for use with, say, <code>transform</code>). </p>\n\n<p>See the iterators concept in the <a href="http://en.cppreference.com/w/cpp/iterator" rel="noreferrer">C++ Documentation</a>:</p>\n\n<ul>\n<li>Input Iterator</li>\n<li>Output Iterator</li>\n<li>Forward Iterator</li>\n<li>Bidirectional Iterator</li>\n<li>Random Access Iterator</li>\n</ul>\n\n<p>These are far more interesting and powerful compared to Java/C#\'s puny iterators. Hopefully these conventions will be codified using C++0x\'s <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Concepts" rel="noreferrer">Concepts</a>.</p>\n'}, {'answer_id': 56396, 'author': 'Marcus Downing', 'author_id': 1000, 'author_profile': 'https://Stackoverflow.com/users/1000', 'pm_score': 1, 'selected': False, 'text': '<p>Iterators are only equivalent to pointers in the trivial case of iterating over the contents of an array in sequence. An iterator could be supplying objects from any number of other sources: from a database, from a file, from the network, from some other calculation, etc.</p>\n'}, {'answer_id': 56401, 'author': 'Anthony Williams', 'author_id': 5597, 'author_profile': 'https://Stackoverflow.com/users/5597', 'pm_score': 3, 'selected': False, 'text': '<p>A pointer to an array element is indeed an iterator into the array.</p>\n\n<p>As you say, in Java, an iterator has more knowledge of the underlying container than in C++. C++ iterators are general, and a <em>pair</em> of iterators can denote any range: this can be a sub-range of a container, a range over multiple containers (see <a href="http://www.justsoftwaresolutions.co.uk/articles/pair_iterators.pdf" rel="noreferrer">http://www.justsoftwaresolutions.co.uk/articles/pair_iterators.pdf</a> or <a href="http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/zip_iterator.html" rel="noreferrer">http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/zip_iterator.html</a>) or even a range of numbers (see <a href="http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/counting_iterator.html" rel="noreferrer">http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/counting_iterator.html</a>)</p>\n\n<p>The iterator categories identify what you can and can\'t do with a given iterator.</p>\n'}, {'answer_id': 56419, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 5, 'selected': False, 'text': "<p>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 <em>just behind</em> the last element.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>On the other extreme, you have C pointers which correspond exactly to C++' concept of a random access iterator.</p>\n\n<p>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.</p>\n"}, {'answer_id': 56441, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 1, 'selected': False, 'text': '<p>C++ library (the part formerly known as STL) iterators are designed to be compatible with pointers. Java, without pointer arithmetic, had the freedom to be more programmer-friendly.</p>\n\n<p>In C++ you end up having to use a pair of iterators. In Java you either use an iterator or a collection. Iterators are supposed to be the glue between algorithm and data structure. Code written for 1.5+ rarely need mention iterators, unless it is implementing a particular algorithm or data structure (which the vary majority of programmers have no need to do). As Java goes for dynamic polymorphism subsets and the like are much easier to handle.</p>\n'}, {'answer_id': 56795, 'author': 'Douglas Leeder', 'author_id': 3978, 'author_profile': 'https://Stackoverflow.com/users/3978', 'pm_score': 2, 'selected': False, 'text': '<p>To me the fundamental difference is that Java Iterators point between items, whereas C++ STL iterators point at items.</p>\n'}, {'answer_id': 58660, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 2, 'selected': False, 'text': "<p>C++ iterators are a generalization of the pointer concept; they make it applicable to a wider range of situations.  It means that they can be used to do such things as define arbitrary ranges.</p>\n\n<p>Java iterators are relatively dumb enumerators (though not so bad as C#'s; at least Java has ListIterator and can be used to mutate the collection).</p>\n"}, {'answer_id': 161439, 'author': 'Aaron', 'author_id': 14153, 'author_profile': 'https://Stackoverflow.com/users/14153', 'pm_score': 4, 'selected': False, 'text': '<p>As mentioned, Java and C# iterators describe an intermixed position(state)-and-range(value), while C++ iterators separate the concepts of position and range.  C++ iterators represent \'where am I now\' separately from \'where can I go?\'.</p>\n\n<p><strong>Java and C# iterators can\'t be copied.  You can\'t recover a previous position.  The common C++ iterators can.</strong></p>\n\n<p>Consider <a href="http://codepad.org/5D2xR6EV" rel="noreferrer">this example</a>:</p>\n\n<pre><code>// for each element in vec\nfor(iter a = vec.begin(); a != vec.end(); ++a){\n  // critical step!  We will revisit \'a\' later.\n  iter cur = a; \n  unsigned i = 0;\n  // print 3 elements\n  for(; cur != vec.end() &amp;&amp; i &lt; 3; ++cur, ++i){\n      cout &lt;&lt; *cur &lt;&lt; " ";\n  }\n  cout &lt;&lt; "\\n";\n}\n</code></pre>\n\n<p>Click the above link to see program output.</p>\n\n<p>This rather silly loop goes through a sequence (using forward iterator semantics only), printing each contiguous subsequence of 3 elements exactly once (and a couple shorter subsequences at the end).  But supposing N elements, and M elements per line instead of 3, this algorithm would still be O(N*M) iterator increments, and O(1) space.</p>\n\n<p>The Java style iterators lack the ability to store position independently.  You will either</p>\n\n<ul>\n<li>lose O(1) space, using (for example) an array of size M to store history as you iterate</li>\n<li>will need to traverse the list N times, making O(N^2+N*M) time</li>\n<li>or use a concrete Array type with GetAt member function, losing genericism and the ability to use linked list container types.</li>\n</ul>\n\n<p>Since only forward iteration mechanics were used in this example, i was able to swap in a list with <a href="http://codepad.org/aRsFuoA4" rel="noreferrer">no problems</a>.  This is critical to authoring generic algorithms, such as search, delayed initialization and evaluation, sorting, etc.</p>\n\n<p>The inability to retain state corresponds most closely to the C++ STL input iterator, on which very few algorithms are built.  </p>\n'}, {'answer_id': 29954778, 'author': 'Neo M Hacker', 'author_id': 983732, 'author_profile': 'https://Stackoverflow.com/users/983732', 'pm_score': 2, 'selected': False, 'text': '<p>There are plenty of good answers about the differences, but I felt the thing that annoys me the most with Java iterators wasn\'t emphasized--You can\'t read the current value multiple times. This is really useful in a lot of scenarios, especially when you are merging iterators. </p>\n\n<p>In c++, you have a method to advance the iterator and to read the current value. Reading its value doesn\'t advance the iteration; so you can read it multiple times. This is not possible with Java iterators, and I end up creating wrappers that do this.</p>\n\n<p>A side note: one easy way to create a wrapper is to use an existing one--<a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/PeekingIterator.html" rel="nofollow">PeekingIterator</a> from Guava. </p>\n'}]
['https://Stackoverflow.com/questions/56347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/445087/']