Bidirectional Iterator
Bidirectional iterator performs forward and backward moving
You're viewing an older version of this page (#4214). View the current version.
Description
Bidirectional iterator is like a http://codecogs.com/reference/computing/stl/iterators/forward_iterator.php"forward iterator" with the difference that bidirectional iterator can be decremented.
Operations
| Expression | Description |
| *i | Provides read access to the actual element |
| i->m | Provides read access to a member of the actual element |
| ++i | Steps forward and returns new position (when not null) |
| i++ | Steps forward and returns old position (when not null) |
| --i | Steps backward and returns new position (when not null) |
| i-- | Steps backward and returns old position (when not null) |
| i1==i2 | Returns if i1 is equal to i2 |
| i1!=i2 | Returns if i1 is not equal to i2 |
| TYPE() | Creates iterator (default constructor) |
| TYPE(i) | Copies iterator (copy constructor) |
| i1=i2 | Assigns an iterator |
References
- http://www.tenouk.com/
- Nicolai M. Josuttis: "The C++ Standard Library"
Example 1
Problem
This program illustrates typical uses of the default list class iterator (which is a bidirectional iterator), and shows the use of operators =, ++, --, != and * with list class iterators.
Workings
#include <iostream>
#include <string>
#include <list>
using namespace std;
int main()
{
list<int> lst1(8);
cout <<"\nFirst we enter some integer squares into "
"a list of size 8, and then display: \n";
//Create and initialize an iterator.
list<int>::iterator p = lst1.begin();
int i = 0;
while(p != lst1.end())
{
*p = i*i; //Assign i*i to list lst via iterator p.
p++; //Advance the iterator **after** using it.
i++; //Increment the value to be squared.
}
p = lst1.begin();
while(p != lst1.end())
cout <<*p++<<" ";
cout <<"\nNext we double the values in the list and "
"re-display (backwards this time): \n";
p = lst1.begin();
while(p != lst1.end())
{
*p = *p * 2;
p++;
}
//This time, initialize the iterator to lst1.end().
//And decrement the iterator **before** using it!
p = lst1.end();
while(p != lst1.begin())
cout <<*--p<<" "; //Note *--p "idiom".
return 0;
}Solution
Output:
First we enter some integer squares into a list of size 8, and then display:
0 1 4 9 16 25 36 49
Next we double the values in the list and re-display (backwards this time):
98 72 50 32 18 8 2 0
See Also
- http://www.codecogs.com/reference/computing/stl/iterators/input_iterator.php "Input Iterator"
- http://codecogs.com/reference/computing/stl/iterators/output_iterator.php"Output Iterator"
- http://codecogs.com/reference/computing/stl/iterators/forward_iterator.php "Forward Iterator"
- http://codecogs.com/reference/computing/stl/iterators/random_access_iterator.php"Random Access Iterator"