Iterators Iterator Notation Iterator Example

advertisement
CS182-Lecture 22
13 May 2003
Iterators
!
A mechanism for sequentially accessing
STL containers (list, vector, …)
!
!
!
Especially important for lists since they do
not have a subscript operator ([])
Provide access to the “next” and
“previous” links in a list
(For those familiar with pointers,)
iterators are similar to pointers
1
Iterator Notation
!
Declaration
!
!
std::vector<TYPE>::iterator NAME;
Operators
!
!
!
* Access data element (dereferencing)
++, -- Advance or retreat in the vector
==, != Comparison
!
NOTE: No < or >
2
Iterator Example
!
Square and display all the elements
in a list
#include <list>
std::list<int> myData; First in the list
…
for (std::list<int>::iterator iter
= myData.begin();
iter != myData.end(); ++iter)
{
*iter = *iter * *iter;
cout << *iter << endl;
}
© Eric A. Durant, PhD
One past the end
3
1
CS182-Lecture 22
13 May 2003
Iterators in a Linked List
Main List Cell
Size
.begin()
Data
Data
First
Last
…
…
Data
…
.end()
4
Validity of iterators
vector<int> vi;
vi.push_back(2);
vi.push_back(-7);
vector<int>::iterator it
= vi.begin() + 1; // can’t do for list!
cout << *it; // -7
vi.erase(it); // removes –7
// now “it” is no longer a valid iterator
it--; // bug; using "it"
// may crash program now
5
Iterator Variations
!
Standard iterators can be used to change a
list item
!
!
!
!
!
*iter = newValue;
Special iterators for const containers
list<TYPE>::const_iterator citer;
Required for const containers (e.g., display function taking
const vector<Buddy>& bl)
Reverse iterators
!
!
list<TYPE>::reverse_iterator riter;
list<TYPE>::const_reverse_iterator criter;
6
© Eric A. Durant, PhD
2
CS182-Lecture 22
13 May 2003
Why use iterators?
!
We can index a vector (e.g.,
vector<Buddy>), so why use
iterators?
!
!
Makes change to other container types
(e.g., list) very easy.
Required for various STL algorithms
(sorting, etc.)
7
More on Reverse Iterators
!
For going from end to beginning
!
!
!
++ Retreats
-- Advances
Bounds
!
rbegin() – Last
!
rend() – One “before” the first
8
Other iterator Member
Functions
!
These member functions need
iterators
!
insert – (where, what)
!
erase – (where) or (start, finish)
!
find – Locate specified item
(start, finish, what)
9
© Eric A. Durant, PhD
3
CS182-Lecture 22
13 May 2003
Iterator Example (1)
!
Our version of the find member function
list<int>::iterator find(list<int>& data,
int value)
{
list<int>::iterator retIter
= data.end();
bool done = false;
list<int>::iterator iter
= data.begin();
10
Iterator Example (2)
while (!done && iter != data.end()) {
if (*iter == value) {
retIter = iter;
done = true;
}
else
++iter;
}
return retIter;
}
11
Design Exercise
!
Given a list of ints, create a
vector that contains all the elements
that are >= 15
32 -7 3 15 17 3 19 0 22 17
12
© Eric A. Durant, PhD
4
Download