Based on On Iteration by Andrei Alexandrescu
*p--qq--p++p < qProvide a way to access the elements of an aggregate object sequentially without exposing its underlying representation
First() is replaced by a copyIterators tie data structures and algorithms together *
|
| Name | C/C++ | C++11 |
|---|---|---|
| dereference | *p |
|
| increment | ++p, (p++) |
|
| decrement | --p, (p--) |
|
| copy | curp = p |
|
| comparison | p != end |
|
| addition n | p + n |
std::next(p, n) |
| subtraction n | p - n |
std::prev(p, n) |
| increment n | p += n |
std::advance(p, n) |
| decrement n | p -= n |
|
| indexing | p[n] |
|
| distance | p - begin |
std::distance(begin, p) |
begin is an iterator to the first elementend is an iterator past the last element!= instead of < because sequential elements may not be adjacentauto to make declaration easierauto also makes the code adaptable to multiple sequence containers| Term | C/C++ | Order of Operations |
|---|---|---|
| pre-increment | ++p |
p += 1;return p; |
| post-increment | p++ |
auto t = p;p += 1;return t; |
| pre-decrement | --p |
p -= 1;return p; |
| post-decrement | p-- |
auto t = p;p -= 1;return t; |
++p (pre-increment) instead of p++ (post-increment)--p (pre-decrement) instead of p-- (post-decrement)| Description | Method |
|---|---|
| Iterator to first element | v.begin() |
| Iterator past the end of the vector | v.end() |
const Iterator form of v.begin() |
v.cbegin() |
const Iterator form of v.end() |
v.cend() |
| Reverse iterator to the element preceding the first element | v.rbegin() |
| Reverse iterator to the last element in the vector | v.rend() |
const Iterator form of v.rbegin() |
v.crbegin() |
const Iterator form of v.rend() |
v.crend() |
| Category | *p |
++p |
p++ |
curp = p |
p != end |
--p |
p-- |
p[5] |
p += 5 |
p - begin |
|---|---|---|---|---|---|---|---|---|---|---|
| forward | ✔ | ✔ | ✔ | ✔ | ✔ | |||||
| bidirectional | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | |||
| random-access | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ |
std::array, std::vector, std::deque, std::list, std::forward_liststd::set, std::map, std::multiset, std::multimapstd::unordered_set, std::unordered_map, std::unordered_multiset, std::unordered_multimapstd::stringstd::stack, std::queue, std::priority_queue do not provide iterators