{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Iterators and Algorithms

# Iterators and Algorithms - Lecture 9a Standard Template...

This preview shows pages 1–7. Sign up to view the full content.

Lecture 9a Standard Template Library (STL) Part II: Iterators and Algorithms

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Iterators Purpose To design generic algorithms that may work on different data structures Template functions: algorithm to work on data elements of different types, but with same structures Iterators are objects used to cycle through the elements stored in container Same concepts as pointers Unify algorithms so that they work using the same syntax for different containers
Using an Iterator vector<int>::iterator p = a.begin(); while (p != a.end()) { cout << *p << endl; p++;} //possible mismatch list<int> one; list<int> two; list<int>::iterator p = one.begin(); while (p!= two.end()) { … } //cares must be taken to ensure that elements of iterator pair always come from the same container

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Operators with Iterators (1) The * operator Access the value associated with an iterator The ++ operator Advance an iterator to the next element The equality operator (== and !=) Compares two iterators The ++ and – operators Allowing iterators to move both forward and backward through the container
Operators with Iterators (2) Subscript operator [] P[n]: indicates a reference to the nth element after p. vector<int>::iterator p = a.begin(); ++p; ++p; cout << p[3] << endl; //print out a[5] iterator + n Reference to the n th element after p iterator – iterator Returning the number of elements between p and q

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Containers and Iterator Operators Not all operators are supported by all iterators List containers do not support the subscript operator Member functions in the vector and deque classes return random access iterators Lists, sets and maps return bidirectional iterators
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 25

Iterators and Algorithms - Lecture 9a Standard Template...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online