03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

122 CHAPTER 4. GENERIC PROGRAMMING<br />

Data Structures Algorithms<br />

vector<br />

set<br />

map<br />

queue<br />

: :<br />

Iterators<br />

Figure 4.2: Central role of iterators in STL<br />

copy<br />

search<br />

replace<br />

Evidently, not all algorithms can be implemented on every data structure. Which algorithm<br />

works on a given data structure depends on the kind of iterator provided by the container.<br />

Iterators can be distinguished by the <strong>for</strong>m of access:<br />

InputIterator: an iterator concept <strong>for</strong> reading the referred entries.<br />

OutputIterator: an iterator concept <strong>for</strong> writing to the referred entries.<br />

Note that the ability to write does not imply readability, e.g., an ostream iterator is an STL<br />

interface used to write to output streams like files opened in write mode. Another differentiation<br />

of iterators is the <strong>for</strong>m of traversal:<br />

ForwardIterator: a concept <strong>for</strong> iterators that can pass from one element to the next, i.e. types<br />

that provide an operator++. It is a refinement of InputIterator and OutputIterator. In contrast<br />

to those, ForwardIterator they allows <strong>for</strong> traversing multiple times.<br />

BidirectionalIterator: a concept <strong>for</strong> iterators with step-wise <strong>for</strong>ward and backward traversal,<br />

i.e. types with operator++ and operator−−. It refines ForwardIterator.<br />

RandomAccessIterator: a concept <strong>for</strong> iterators that can increment their position by an arbitrary<br />

integer, i.e. types that also provide operator[]. It refines BidirectionalIterator.<br />

Data structures that provide more refined iterators (e.g. modeling RandomAccessIterator) can be<br />

used in more algorithms. Dually, algorithm implementations that require less refined iterators<br />

(like InputIterator) can be applied to more data structures. The interfaces are designed with<br />

backward compatibility in mind and old-style pointers can be used as iterators.<br />

All standard container templates provide a rich and consistent set of iterator types. The<br />

following very simple example shows a typical use of iterators:<br />

std::list l ;<br />

<strong>for</strong> (std::list::const iterator it = l.begin(); it != l.end(); ++it) {<br />

std::cout ≪ ∗it ≪ std::endl;<br />

}<br />

sort<br />

: :

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!