| Instructor: | David Goldschmidt, Ph.D. |
|---|---|
| Office Hours: | after class |
| Email: | click here to email me |
Iterator Operations:
vector<double>::iterator p; list<string>::iterator q;
vector<double> v; vector<double>::iterator p; p = v.begin() + i; // i-th location in the vector list<string> r; list<string>::iterator q; q = r.begin(); // first entry in the list
// use of *p and *q below are as l-values: *p = 3.14; *q = "Hello"; // use of *q below is as an r-value: cout << *q << endl;
// move p to the next location in the vector ++p; // move q to the previous location in the list q--;
list<string> words;
// ... populate the list ...
// iterate through all elements of the list:
for ( list<string>::iterator p = words.begin() ; p != words.end() ; p++ ) {
cout << *p << " " << p->size() << '\n';
}
// TO DO: change above for loop into a while loop
vector<double> v; vector<double>::iterator p; p = v.begin(); *p = 3.14; // changes entry 0 in v vector<double> w; p = w.begin() + 2; *p = 2.78; // changes entry 2 in w vector<string> a; p = a.begin(); // !!! compilation error due to type mismatch !!!
Vector Iterators:
Vector (and string) iterators have special capabilities that other container iterators (e.g. list) do not have, as described below.
p = v.begin() + i;
p = p + 5; // moves p exactly 5 locations further in the vector
Iterators vs. Indexes for Vectors and Strings:
vector<double> a( 10, 2.5 ), b( 20, 1.1 ); vector<string> c( 3, string( "hi" ) ); vector<double>::iterator p = a.begin() + 5; unsigned int i = 5;
*p = 6.0; // change the contents of vector a.
// i is not "attached" to vector a in any way cout << a[i] << endl;
Lists vs. Vectors:
Erase:
list<int> s; // ... populate s ... list<int>::iterator p = s.begin(); p++; list<int>::iterator q = s.erase( p ); // after calling the function erase(): // – the integer stored in the second entry of the list has been removed // – the size of the list has shrunk by one // – iterator p does not refer to a valid entry // – iterator q refers to the item that was the third entry and is now the second
list<int>::iterator p = s.begin(); p++; p = s.erase( p );
Insert:
list<string>::iterator p = words.begin(); // insert string "Hello" at the beginning of the list p = words.insert( p, string( "Hello" ) ); // ... populate the list ... // refer to the element beyond the last element in the list list<string>::iterator p = words.end(); p = words.insert( p, string( "Bye" ) ); p = words.insert( p, string( "Good" ) ); // the list ends with: ... "Good" "Bye"