In principle, there is a general idea of how they work, but in the book I saw this: "Iterators obey the principle of pure abstraction, that is, any object that behaves as an iterator is an iterator," as understood?
1 answer
Apparently, the following is meant: any object that behaves as an iterator (that is, at a minimum, having dereferencing ( * ) and promotion ( ++ ) operations) can be used where an iterator is expected.
This is essentially a consequence of weak (duck) typing used in C ++ templates.
Example :
#include <iostream> #include <vector> using namespace std; template <typename Iterator> void print_container(const Iterator& from, const Iterator& to) { bool first = true; for (Iterator it = from; it != to; ++it) { if (!first) cout << ", "; first = false; cout << *it; } cout << endl; } int main() { int a[] = { 1, 2, 3 }; vector<int> v = { 11, 12, 13 }; print_container(&a[0], &a[0] + (sizeof(a) / sizeof(a[0]))); print_container(begin(a), end(a)); print_container(begin(v), end(v)); return 0; } Pointer to int ( &a[0] ) copes well with the role of an iterator.
- Thank! And could you tell the off-topic why in the interval (istream_iterator <int> (cin), istream_iterator <int> ()) the second argument acts as a final iterator? - Robert Pinkman
- one@Robert Pinkman: Well, the developers of the standard library decided so. According to the documentation :>
istream_iterator(): Constructs the end-of-stream iterator. - VladD
|