Download presentation
Presentation is loading. Please wait.
1
abstracting away the data structure
Iterators abstracting away the data structure
2
Uphill...both ways When I was your age*
3
*"but we're all different ages!"
Uphill...both ways When I was your age* *"but we're all different ages!"
4
Uphill...both ways When I was your age int array[5] = {1, 2, 3, 4, 5};
int i; for(i=0; i<5; ++i) { printf("%d\n",array[i]); }
5
Uphill...both ways When I was your age int array[5] = {1, 2, 3, 4, 5};
int *p = array; int *end = array+5; while( p != end ) { printf("%d\n", *p ); ++p; }
6
Uphill...both ways When I was your age int array[5] = {1, 2, 3, 4, 5};
int *p = array; int *end = array+5; while( p != end ) { printf("%d\n", *p ); ++p; }
7
C++ Iterators An iterator is any class that overloads the operators:
< element type > operator *() {...} < iterator type > operator ++() {...} bool operator != (const <iterator type>& other) {...}
8
C++ Iterators Well, those are the requirements for a forward_iterator
This is the only kind that you can (easily) make for a (singly) linked list. But there are others: random_access bidirectional forward input output
9
C++ Iterators But forward_iterators are the minimum required for the kind of loop from the example
10
C++ Iterators std::vector<int> v {1, 2, 3, 4, 5};
std::vector<int>::iterator i = v.begin(); for( ; i != v.end(); ++i ) { std::cout << *i << std::endl; }
11
C++ Iterators std::vector<int> v {1, 2, 3, 4, 5};
for(int i : v ) { std::cout << i << std::endl; }
12
C++ Containers with iteration
The container must implement <iterator type> begin(); <iterator type> end(); End is effectively one element beyond the end of the list
13
STL is based on iterators
template <class input_it, class output_it, class unary_operation> output_it transform( input_it first_in, input_it last_in, output_it first_out, unary_operation op);
14
More fun with iterators
Create a synthetic container that "contains" a transformed version of another container Create an effectively infinite list
15
Generators Some languages make it easy to do some of those last operations In Python, these are called "generators" They look like functions, but the return statement is replaced with a yield statement The yielded value is provided to the caller, but the function state is stored for the next call
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.