Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |
A container may also be reversible, which means that
it can produce iterators that move backward from the end, as well as iterators
that move forward from the beginning. All standard containers support such
bidirectional iteration.
A reversible container has the member functions rbegin( ) (to produce a reverse_iterator selecting the end) and rend( ) (to produce a reverse_iterator indicating one past the beginning ). If the
container is const, rbegin( ) and rend( ) will
produce const_reverse_iterators.
The following example uses vector but will work with
all containers that support iteration:
//: C07:Reversible.cpp
// Using reversible containers.
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "../require.h"
using namespace std;
int main() {
ifstream in("Reversible.cpp");
assure(in, "Reversible.cpp");
string line;
vector<string> lines;
while(getline(in, line))
lines.push_back(line);
for(vector<string>::reverse_iterator r =
lines.rbegin();
r != lines.rend(); r++)
cout << *r << endl;
} ///:~
You move backward through the container using the same
syntax as you do when moving forward through a container with an ordinary
iterator.
Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |