Home | | Object Oriented Programming | Iterators - C++

Chapter: Object Oriented Programming(OOP) : Basic Characteristics of OOP

Iterators - C++

An iterator points to (refers to, denotes) an element of a sequence

ITERATORS

 

n    An iterator points to (refers to, denotes) an element of a sequence

 

n    The end of the sequence is “one past the last element”

 

n    not “the last element”

 

n    That’s necessary to elegantly represent an empty sequence

 

n    One-past-the-last-element isn’t an element

 

n    You can compare an iterator pointing to it

 

n    You can’t dereference it (read its value)

 

n    Returning the end of the sequence is the standard idiom for “not found” or “unsuccessful”


Simple algorithm: find_if()

n   Find the first element that matches a criterion (predicate)

n Here, a predicate takes one argument and returns a bool template<class In, class Pred>

 

In find_if(In first, In last, Pred pred)

{

 

while (first!=last && !pred(*first)) ++first; return first;

 

}

void f(vector<int>& v)

{

 

vector<int>::iterator p = find_if(v.begin(),v.end,Odd());

 if (p!=v.end()) { /* we found an odd number */ }

 

// …

}

Iterator Operators

* dereferencing operator


n   Produces a reference to the object to which the iterator p points

*p

++ point to next element in list


n    Iterator p now points to the element that followed the previous element to which p points

 

++p

-- point to previous element in list


n    Iterator p now points to the element that preceded the previous element to which p points

 

--p

 

 viiterator p = C.begin(), q = C.end(); for(;p!=q; p++) {

 

cout << *p << endl;

}

for(int i=0; i < 10; i++) { cout << C[i] << endl;}


int A[10];


for(int * p = A, i =0; i < 10; i++, p++) { cout << *p << endl;}

 


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Object Oriented Programming(OOP) : Basic Characteristics of OOP : Iterators - C++ |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.