Friday, January 1, 2010

STL ITERATORS- ADVANCE & DISTANCE

ADVANCE:
Belongs to

Advance iterator
Advances the iterator i by n elements.

If i is a Random Access Iterator, the function uses once operator+ or operator-, otherwise, the function uses repeatedly the increase or decrease operator (operator++ or operator--) until n elements have been advanced.

Return value:none

// advance example
#include
#include
#include
using namespace std;

int main () {
list mylist;
for (int i=0; i<10; i++) mylist.push_back (i*10);

list::iterator it = mylist.begin();

advance (it,5);

cout << "The sixth element in mylist is: " << *it << endl;

return 0;
}
OUTPUT:
The sixth element in mylist is: 50



DISTANCE:
Return distance between iterators

Calculates the number of elements between first and last.

If i is a Random Access Iterator, the function uses operator- to calculate this. Otherwise, the function uses repeatedly the increase or decrease operator (operator++ or operator--) until this distance is calculated.

Return value:
The number of increments or decrements needed to get from first to last.

// distance example
#include
#include
#include
using namespace std;

int main () {
list mylist;
for (int i=0; i<10; i++) mylist.push_back (i*10);

list::iterator first = mylist.begin();
list::iterator last = mylist.end();

cout << "The distance is: " << distance(first,last) << endl;

return 0;
}

Output

The distance is: 10

No comments:

Post a Comment