Iterators and Algorithms

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

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

View Full Document Right Arrow Icon
Lecture 9a Standard Template Library (STL) Part II: Iterators and Algorithms
Background image of page 1

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

View Full DocumentRight Arrow Icon
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
Background image of page 2
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
Background image of page 3

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

View Full DocumentRight Arrow Icon
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
Background image of page 4
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
Background image of page 5

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

View Full DocumentRight Arrow Icon
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
Background image of page 6
Image of page 7
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 12/18/2008 for the course CS 256 taught by Professor Dr. yang during the Fall '08 term at Cal Poly Pomona.

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 Right Arrow Icon
Ask a homework question - tutors are online