To understand the overall picture of STL, we need to look at the different categories of iterator required for particular generic algorithms, the next STL building block.
Any of those iterators that satisfy the requirements of output iterators are sometimes referred to as mutable iterators, while those that don’t are referred to as constant iterators.
C++17 adds a sixth kind of iterator, the Contiguous Iterator.
It provides some optimisations above random access iterators in the case where the container elements are stored contiguously.
We will see later that iterators LegacyIterators from C++20.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<char> c;
c.push_back('A');
c.push_back('B');
c.push_back('C');
c.push_back('D');
for (int i=0; i<4;++i)
cout << "c[“ << I << "]=“ << c[i] << endl;
vector<char>::iterator p = c.begin();
cout << "The third entry is “ << c[2] << endl;
cout << "The third entry is “ << p[2] << endl;
cout << "The third entry is “ << *(p+2) << endl;
cout << "Back to c[0].\n";
p = c.begin();
cout << "which has value “ << *p << endl;
cout << "Two steps forward and one step back:\n";
p++;
cout << *p << endl;
p++;
cout << *p << endl;
p--;
cout << *p << endl;
return 0;
}
c[0]=A
c[1]=B
c[2]=C
c[3]=D
The third entry is C
The third entry is C
The third entry is C
Back to c[0].
which has value A
Two steps forward and one step back:
B
C
B
Use rbegin() and rend().
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<char> c;
c.push_back('A');
c.push_back('B');
c.push_back('C');
cout << "Forward:\n";
vector<char>::iterator p;
for (p=c.begin(); p!=c.end(); p++) cout<< *p << " ";
cout << endl;
cout << "Reverse:\n";
vector<char>::reverse_iterator rp;
for(rp=c.rbegin(); rp!=c.rend(); rp++) cout<< *rp <<" ";
cout << endl;
return 0;
}
Two useful stream iterators
istream_iterator<type> isIterator(istream&);
ostream_iterator<type> osIterator(ostream&);
ostream_iterator<type> osIterator(ostream&, char* deLimit);
int main()
{
vector<int> x;
copy(istream_iterator<int>(cin), istream_iterator(), back_inserter(x));
vector<int>::iterator p = remove_if(x.begin(), x.end(), is_even);
x.erase(p, x.end());
copy(x.begin(), x.end(), ostream_iterator<int>(cout, "\n "));
}
int main()
{
double value1, value2;
cout << "Please, insert two values: ";
istream_iterator<double> eos; // end-of-stream iterator
istream_iterator<double> iit (std::cin); // stdin iterator
if (iit!=eos)
value1 = *iit;
++iit;
if (iit!=eos)
value2 = *iit;
cout << value1 << "*" << value2 << "=" << (value1*value2) << '\n';
}