Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Iterator
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===C++=== The [[C++]] language makes wide use of iterators in its [[C++ Standard Library|Standard Library]] and describes several categories of iterators differing in the repertoire of operations they allow. These include ''forward iterators'', ''bidirectional iterators'', and ''random access iterators'', in order of increasing possibilities. All of the standard container template types provide iterators of one of these categories. Iterators generalize pointers to elements of an array (which indeed can be used as iterators), and their syntax is designed to resemble that of [[C (programming language)|C]] [[pointer arithmetic]], where the <code>*</code> and <code>-></code> operators are used to reference the element to which the iterator points and pointer arithmetic operators like <code>++</code> are used to modify iterators in the traversal of a container. Traversal using iterators usually involves a single varying iterator, and two fixed iterators that serve to delimit a range to be traversed. The distance between the limiting iterators, in terms of the number of applications of the operator <code>++</code> needed to transform the lower limit into the upper one, equals the number of items in the designated range; the number of distinct iterator values involved is one more than that. By convention, the lower limiting iterator "points to" the first element in the range, while the upper limiting iterator does not point to any element in the range, but rather just beyond the end of the range. For traversal of an entire container, the <code>begin()</code> method provides the lower limit, and <code>end()</code> the upper limit. The latter does not reference any element of the container at all but is a valid iterator value that can be compared against. The following example shows a typical use of an iterator. <syntaxhighlight lang="cpp"> std::vector<int> items; items.push_back(5); // Append integer value '5' to vector 'items'. items.push_back(2); // Append integer value '2' to vector 'items'. items.push_back(9); // Append integer value '9' to vector 'items'. for (auto it = items.begin(), end = items.end(); it != end; ++it) { // Iterate through 'items'. std::cout << *it; // And print value of 'items' for current index. } // In C++11, the same can be done without using any iterators: for (auto x : items) { std::cout << x; // Print value of each element 'x' of 'items'. } // Both of the for loops print "529". </syntaxhighlight> Iterator types are separate from the container types they are used with, though the two are often used in concert. The category of the iterator (and thus the operations defined for it) usually depends on the type of container, with for instance arrays or vectors providing random access iterators, but sets (which use a linked structure as implementation) only providing bidirectional iterators. One same container type can have more than one associated iterator type; for instance the <code>std::vector<T></code> container type allows traversal either using (raw) pointers to its elements (of type <code>*<T></code>), or values of a special type <code>std::vector<T>::iterator</code>, and yet another type is provided for "reverse iterators", whose operations are defined in such a way that an algorithm performing a usual (forward) traversal will actually do traversal in reverse order when called with reverse iterators. Most containers also provide a separate <code>const_iterator</code> type, for which operations that would allow changing the values pointed to are intentionally not defined. Simple traversal of a container object or a range of its elements (including modification of those elements unless a <code>const_iterator</code> is used) can be done using iterators alone. But container types may also provide methods like <code>insert</code> or <code>erase</code> that modify the structure of the container itself; these are methods of the container class, but in addition require one or more iterator values to specify the desired operation. While it is possible to have multiple iterators pointing into the same container simultaneously, structure-modifying operations may invalidate certain iterator values (the standard specifies for each case whether this may be so); using an invalidated iterator is an error that will lead to undefined behavior, and such errors need not be signaled by the run time system. Implicit iteration is also partially supported by C++ through the use of standard function templates, such as <code>[https://en.cppreference.com/w/cpp/algorithm/for_each std::for_each()]</code>, <code>[https://en.cppreference.com/w/cpp/algorithm/copy std::copy()]</code> and <code>[https://en.cppreference.com/w/cpp/algorithm/accumulate std::accumulate()]</code>. When used they must be initialized with existing iterators, usually <code>begin</code> and <code>end</code>, that define the range over which iteration occurs. But no explicit iterator object is subsequently exposed as the iteration proceeds. This example shows the use of <code>for_each</code>. <syntaxhighlight lang="cpp"> ContainerType<ItemType> c; // Any standard container type of ItemType elements. void ProcessItem(const ItemType& i) { // Function that will process each item of the collection. std::cout << i << std::endl; } std::for_each(c.begin(), c.end(), ProcessItem); // A for-each iteration loop. </syntaxhighlight> The same can be achieved using <code>std::copy</code>, passing a <code>[https://en.cppreference.com/w/cpp/iterator/ostream_iterator std::ostream_iterator]</code> value as third iterator: <syntaxhighlight lang="cpp"> std::copy(c.begin(), c.end(), std::ostream_iterator<ItemType>(std::cout, "\n")); </syntaxhighlight> Since [[C++11]], [[C++11#Lambda functions and expressions|lambda function]] syntax can be used to specify to operation to be iterated inline, avoiding the need to define a named function. Here is an example of for-each iteration using a lambda function: <syntaxhighlight lang="cpp"> ContainerType<ItemType> c; // Any standard container type of ItemType elements. // A for-each iteration loop with a lambda function. std::for_each(c.begin(), c.end(), [](const ItemType& i) { std::cout << i << std::endl; }); </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)