Presentation is loading. Please wait.

Presentation is loading. Please wait.

ITERATORS Acknowledgement: THE Slides are Prepared FROM SLIDES PROVIDED By NANCY M. AMATO AND Jory Denny.

Similar presentations


Presentation on theme: "ITERATORS Acknowledgement: THE Slides are Prepared FROM SLIDES PROVIDED By NANCY M. AMATO AND Jory Denny."— Presentation transcript:

1 ITERATORS Acknowledgement: THE Slides are Prepared FROM SLIDES PROVIDED By NANCY M. AMATO AND Jory Denny

2 Standard Template Library
A general purpose library of data structures (containers) and algorithms communicating through iterators. Plug each piece together and use in different applications. #include <vector> #include <algorithm> int main(){ int myArray[4]={2, 8, 5, 3}; std::vector<int> v(myArray, myArray+4); std::sort(v.begin(), v.end()); } vector sort container generic algorithm iterator

3 Containers Container is an object storing other objects which can be accessed by iterators Let 𝑋 be a container, then some important associated types: X::value_type – type of data stored in the container X::iterator – type of iterator for the container X::const_iterator

4 Containers Valid expressions 𝑎.begin – beginning of container
𝑎.end – one past the last element of container 𝑎.size – size of container 𝑎.empty – does the container have anything in it?

5 Iterators sort Iterators are used to point to other objects.
Iterators play an interface between data structures and algorithms Main operations advance(), next(), operator++ Dereference – operator∗(), operator→() vector sort container generic algorithm iterator

6 Iterators Forward Iterator – Only allows traversal from begin to end
Bidirectional Iterator – Allows traversal in both directions (reversed order) Random Access Iterator – arbitrarily access elements in any order etc. Algorithms are defined for certain types of iterators, i.e., sort is only defined for random access iterating

7 Example Create a vector containing integer values
int myArray[4]={2, 8, 5, 3}; std::vector<int> v(myArray, myArray+4); Iterate over the vector and output each integer for(vector<int>::iterator it = v.begin(); i != v.end(); ++it) cout<<*(it); Iterate over the vector using random access iterators to output each value for(size_t i = 0; i < v.size(); ++i) cout<<*(v.begin() + i);


Download ppt "ITERATORS Acknowledgement: THE Slides are Prepared FROM SLIDES PROVIDED By NANCY M. AMATO AND Jory Denny."

Similar presentations


Ads by Google