Iterator classification and capabilities:
The input iterator can only read elements once. If the input iterator is copied and both the original iterator and the new generated replica are read forward, different values may be traversed. The output iterator is similar.
C ++ does not allow modification of temporary values of any basic types (including pointers), but for struct, class does.
Therefore:
12 |
vector<int> ivec; sort(++ivec.begin(), ivec.end()); |
It may fail, depending on the actual version of the vector.
C ++ annotation Library provides three auxiliary functions for the iterator
①. Advance () Forward (or backward) Multiple Elements
12 |
#include <iterator>void advance(InputIterator & pos, Dist n) |
Note: For Bidirectional iterator or Random Access iterator, n can be a negative value, indicating that it is backward
②. Distance () processes the distance between iterators
12 |
#include <iterator> Dist distance (InputIterator pos1, InputIterator pos2) |
③. Iter_swap () can exchange the content referred to by two iterators.
12 |
#include <algorithm> void iter_swap(ForwardIterator pos1, ForwardIterator pos2) |
Note: It is not an exchange iterator!
Reverse (Reverse) iterator of iterator Adapter
For reverse iterator, the actual location is not the same as the location indicated by the logic:
Eg.
12345678910111213141516171819 |
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> coll; for (int i=1; i<=9; ++i) { coll.push_back(i); } vector<int>::iterator pos; pos = find (coll.begin(), coll.end(),5); cout << "pos: " << *pos << endl; vector<int>::reverse_iterator rpos(pos); cout << "rpos: " << *rpos <<endl; } |
The result is:
Pos: 5
Rpos: 4
This is the internal mechanism diagram of reverse iterator (*):
We can see that the [begin (), end () and [rbegin (), rend () intervals are the same!
The base () function can convert the reverse iterator back to the normal iterator.
Eg.
Note:
1 |
vector<int>::reverse_iterator rpos(pos); |
The iterator can be assigned to the reverse iterator for implicit conversion, while the reverse iterator can only be converted to a normal iterator using the base () function.
This part has a lot of content, so we need to take P264 ~ Seriously ~ P270.
Insert (Insert) iterator of iterator Adapter
Stream iterator of iterator Adapter
Osream stream iterator:
Istream stream iterator
Comprehensive code:
12345678910111213141516171819 |
// Author: Tanky Woo // Blog: www.WuTianQi.com #include <iostream> #include <vector> #include <iterator> using namespace std; int main() { istream_iterator<int> cinPos(cin); istream_iterator<int> cinEnd; ostream_iterator<int> coutPos(cout, " "); while(cinPos != cinEnd) *coutPos++ = *cinPos++; return 0; } |