| Using Iterators |
Note that pointers in C++ satisfy all of the requirements for iterators, as pointer arithmetic is well defined. In particular, if elts is declared to be an array, elts is a pointer to the first element of the array. Thus if we have:
const int SIZE = 100;
double elts[SIZE];
...
sort(elts, elts+SIZE)
works fine.
A useful built-in function is copy that is used to copy portions of one container class to another. Thus if have
string elts[5] = {``a'', ``b'', ``c'',''d'',''e''};
vector<string> letters[5];
copy(elts, elts+5, letters.begin())
copies all 5 elts to letters.
We can define generic operators on containers as in genericPrint.cpp:
#include <iostream>
#include <vector>
using namespace std;
template <typename Container>
void print(const Container & c, ostream & out = cout) {
typename Container::const_iterator itr;
for (itr = c.begin(); itr != c.end(); ++itr) {
out << *itr << " ";
}
out << endl;
}
int main() {
vector<int> vec;
vec.push_back(12);
vec.push_back(47);
print(vec);
return 0;
}
C++ is smart enough to figure out how to instantiate template function to correct type. Note the extra "typename" is necessary before he name Container when used as a prefix.
| Using Iterators |