|
| 1 | +--- |
| 2 | +title: "Back To Basics: Iterators by Nicolai Josuttis" |
| 3 | +date: 2024-11-22 |
| 4 | +url: https://www.bilibili.com/video/BV1BC4y1R7iL?p=30 |
| 5 | +--- |
| 6 | + |
| 7 | +other talk from this reporter: [markdown](../2021/back_to_basics_lambdas.md) |
| 8 | + |
| 9 | +Loop over array. |
| 10 | + |
| 11 | +- with index |
| 12 | +- with pointer |
| 13 | + |
| 14 | +Iterators: generalization of pointers that iterate |
| 15 | + |
| 16 | +`begin`and`end` |
| 17 | + |
| 18 | +note: end is not the element. It's a half one range. It's no need to deal with empty collections. |
| 19 | + |
| 20 | +## Why Iterators? |
| 21 | + |
| 22 | +Iterators can deal with multi data structure. |
| 23 | + |
| 24 | +Used by the range-based for loop. |
| 25 | + |
| 26 | +`const_iterator` means the element the iterator refers to is const. This is also equals to `cbegin`and`cend` |
| 27 | + |
| 28 | +iterators have different categories. |
| 29 | + |
| 30 | +- random access iterator: can jump to and compare with other position |
| 31 | +- bidirectional iterator: can iterate forward and backward |
| 32 | +- forward iterator: can iterate forward only |
| 33 | +- input iterator: can read elements only once |
| 34 | +- contiguous range/iterator(since c++ 20):support for std::ranges::data() |
| 35 | + |
| 36 | +note: deque is a array of a array so it's a random access iterator but not a contiguous iterator |
| 37 | + |
| 38 | +## Iterator and Algorithms |
| 39 | + |
| 40 | +iterators as glue interface. |
| 41 | + |
| 42 | +ref:std::max_element |
| 43 | + |
| 44 | +```c++ |
| 45 | +if(result != foo.end()) |
| 46 | +``` |
| 47 | + |
| 48 | +handel the result. |
| 49 | + |
| 50 | +ref:std::accumulate |
| 51 | + |
| 52 | +Algorithms are generic |
| 53 | + |
| 54 | +note:std::set sort the element automatic |
| 55 | + |
| 56 | +pure abstraction: everything that behaves like a iterator is a iterator. |
| 57 | + |
| 58 | +Separate data and function. |
| 59 | + |
| 60 | +## Pitfalls of Iterators |
| 61 | + |
| 62 | +append element maybe will change the location of the container. |
| 63 | + |
| 64 | +std::transform()with 4 arguments. Destination need to be a output iterators, and there must be elements to overwrite. |
| 65 | + |
| 66 | +- Need to resize the destination array. |
| 67 | +- using `std::back_inserter` |
| 68 | + |
| 69 | +std::remove remove the elements but doesn't resize the container, it remain the value. Iterator can't remove the elements. |
| 70 | + |
| 71 | +Removing algorithms do note remove, instead they replace removed elements and return the new end. |
| 72 | + |
| 73 | +ref:std::ranges::subrange and std::views::filter |
| 74 | + |
| 75 | +view cache the begin |
| 76 | + |
| 77 | +modification of the element a filter_view::iterator denotes is permitted, but results in undefined behavior if the resulting value does not satisfy the filter predicate. |
| 78 | + |
| 79 | + |
0 commit comments