Docsity

Iterator Operations in Object-Oriented Programming (OOP) - Docsity.com, Slides of Object Oriented Programming

Partial preview of the text

Download Iterator Operations in Object-Oriented Programming (OOP) - Docsity.com and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 42

Iterator Operations

Input Iterators

  • *p
    • Dereference operator (used as rvalue)
  • p1 = p
    • Assignment
  • p1 == p
    • Equality operator
  • p1 != p
    • Inequality operator
  • p->
    • Access Operator

Output Iterators

  • *p
    • Dereference operator (can be used as lvalue)
  • p1 = p
    • Assignment

Bidirectional Iterators

  • Besides the operations of forward iterators

they also support

  • --p
    • Pre-increment operator
  • p--
    • post-decrement operator

Random-access Iterators

  • Besides the operations of bidirectional

iterators, they also support

  • p + i
    • Result is an iterator pointing at p + i
  • p – i
    • Result is an iterator pointing at p – i

…Random-access Iterators

  • p1 <= p
    • Returns true if p1 is before p2 in the container or p1 is equal to p
  • p1 > p
    • Returns true if p1 is after p2 in the container
  • p1 >= p
    • Returns true if p1 is after p2 in the container or p1 is equal to p

Example – Random Access Iterator

typedef std::vector< int > IntVector;

int main() {

const int SIZE = 3; int iArray[ SIZE ] = { 1, 2, 3 }; IntVector iv(iArray, iArray + SIZE); IntVector::iterator it = iv.begin(); cout << “Vector contents: ”; for ( int i = 0; i < SIZE; ++i ) cout << it[i] << ", "; return 0;

}

Example – Bidirectional Iterator

typedef std::set< int > IntSet;

int main() {

const int SIZE = 3; int iArray[ SIZE ] = { 1, 2, 3 }; IntSet is( iArray, iArray + SIZE ); IntSet::iterator it = is.begin(); cout << “Set contents: ”; for (int i = 0; i < SIZE; ++i) cout << it[i] << ", "; // Error return 0;

}

…Example – Bidirectional Iterator

typedef std::set< int > IntSet;

int main() {

const int SIZE = 3; int iArray[ SIZE ] = { 1, 2, 3 }; IntSet is( iArray, iArray + SIZE ); IntSet::iterator it = is.begin(); cout << “Set contents: ”; for ( int i = 0; i < SIZE; ++i ) cout << *it++ << ", "; // OK return 0;

}

…Example – Bidirectional Iterator

typedef std::set< int > IntSet;

int main() {

const int SIZE = 3; int iArray[ SIZE ] = { 1, 2, 3 }; IntSet is( iArray, iArray + SIZE ); IntSet::iterator it = is.end(); cout << “Set contents: ”; for (int i = 0; i < SIZE; ++i) cout << *--it << ", "; return 0;

}

…Sample Output

Set contents: 3, 2, 1,

…Example – Input Iterator

std::istream_iterator< int > inputIt( cin ); x = *inputIt++; y = *inputIt++; z = *inputIt; cout << "x = " << x << endl; cout << "y = " << y << endl; cout << "z = " << z << endl; return 0;

}

…Example – Input Iterator

int main() {

int x = 5; std::istream_iterator< int > inputIt( cin ); *inputIt = x; // Error return 0;

}