110 likes | 251 Views
This lecture covers STL Iterators in C++, emphasizing their advantages over ordinary pointers. Iterators encapsulate access mechanisms and can work with multiple container types using a unified interface. We explore various iterator categories, including Input, Output, Forward, Bidirectional, and Random Access, each with its own features and functionalities. Practical C++ code examples demonstrate how to declare and use iterators with STL containers like lists and vectors, showcasing operations such as insertion, searching, and copying data efficiently.
E N D
EC-241 Object Oriented Programming Lecture 15
STL Iterators • More powerful than ordinary pointers • Encapsulate access mechanism • Can work with multiple types of containers through the same interface
Iterator Categories Random Access Bidirectional Forward Input Output
Iterator Categories • Input: steps forward through a container, reading (but not writing) one item after another • Output: steps forward through a container, writing(but not reading) one item after another • Forward: steps forward through a container, writing (or reading) one item after another • Bidirectional: able to step forward and backward • Random Access: accesses an item instantly, without stepping along
Iterators in ActionData access #include <iostream> #include <list> using namespace std; void main() { intarr[]={2,4,6,8}; list<int> theList; for (int k=0; k<4; k++) //fill list with array elements theList.push_back(arr[k]); list<int>::iteratoriter; //iterator to list of ints for (iter=theList.begin(); iter!=theList.end(); iter++) cout<<*iter<<' '; //2 4 6 8 (output) cout<<endl; }
Iterator: Data insertion and algorithms (find) #include <iostream> #include <algorithm> #include <list> using namespace std; void main() { list<int> theList(5); //empty list holds 5 ints list<int>::iteratoriter; //iterator int data = 0; //fill list with data for(iter = theList.begin(); iter != theList.end(); iter++) *iter = data += 2; //2, 4, 6, 8, 10 iter = find(theList.begin(), theList.end(), 8); //look for number 8 if( iter != theList.end() ) cout << “\nFound 8.\n”; else cout << “\nDid not find 8.\n”; }
Algorithms and Iterators (copy) void main() { int beginRange, endRange; int arr[] = { 11, 13, 15, 17, 19, 21, 23, 25, 27, 29 }; vector<int> v1(arr, arr+10); //initialized vector vector<int> v2(10); //uninitialized vector cout << “Enter range to be copied (example: 2 5): ”; cin >> beginRange >> endRange; vector<int>::iterator iter1 = v1.begin() + beginRange; vector<int>::iterator iter2 = v1.begin() + endRange; vector<int>::iterator iter3; //copy range from v1 to v2 iter3 = copy( iter1, iter2, v2.begin() ); //(it3 -> last item copied) iter1 = v2.begin(); //iterate through range while(iter1 != iter3) //in v2, displaying values cout << *iter1++ << ‘ ‘; }