Standard Template Library – Iterators
You have a container with elements. How will you access it?? You need a hand to pick it up…
Here, iterator is the thing which access the elements of a
container.
Features:
- It traverses the container and hides the internal structure.
- It supports find(),sort() and count() algorithms.
- It access the data as input,output. It can traverse in both forward and bidirectional.
- To access it, use container_type::iterator name.
Let us create a c++ program to illustrate the iterators.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int>
v1 = {100,120,330,440,550};
// let us traverse
the vector using iterator
for
(vector<int>::iterator i1 = v1.begin(); i1 != v1.end(); ++i1)
cout <<
*i1 << " ";
return 0;
}
Output:
100 120 330 440 550
Methods that return the iterator:
‘begin()’ : this function returns the iterator of
beginning point of the container.
‘cbegin()’ : This function returns the constant
iterator.
‘rbegin()’ : This function returns the reverse
iterator.
‘crbegin()’ : This function returns the reverse
constant iterator.
‘end()’ : This function returns the iterator of the
last element.
‘cend()’ : This function returns the end of constant
iterator.
‘rend()’ : This function returns the end of reverse
iterator.
‘crend()’ : This function returns the end of constant
reverse iterator.
C++ program to illustrate iterator functions:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int>
v1 = {110, 200, 330,450, 540, 650};
// iterator as
simple
cout <<
"The Forward iteration is: ";
for (auto i1 =
v1.begin(); i1!= v1.end(); ++i1)
{
cout <<
*i1 << " ";
}
cout <<
endl;
// The Constant iterator is
cout <<
"Forward iteration in read only format: ";
for (auto i1 =
v1.cbegin(); i1 != v1.cend(); ++i1)
{
cout <<
*i1 << " ";
}
cout <<
endl;
// The Reverse iterator is
cout <<
"The Reverse iteration is: ";
for (auto i1 =
v1.rbegin(); i1 != v1.rend(); ++i1)
{
cout <<
*i1 << " ";
}
cout <<
endl;
return 0;
}
Output:
The Forward iteration is: 110 200 330 450 540 650
Forward iteration in read only format: 110 200 330 450 540
650
The Reverse iteration is: 650 540 450 330 200 110
Hope, you understood the concept with programming samples.
Keep Coding!!!!
Comments
Post a Comment