Iterators and Ranges in the C++ Standard Library

85 Просмотры
Издатель
Today we continued our discussion of the C++ Standard Library, focusing on the interaction of how containers, algorithms, and iterators work.

All C++ containers provide these pointer-like objects called "iterators" when you call .begin() or .end() on them. Begin() returns an iterator pointing to the first element in the container, end() returns an iterator pointing to one past the end of the container. You can do math with iterators, such as vec.begin()+3 to point at the element in the vector 3 after the beginning.

Typically you pass pairs of iterators to standard library algorithms (like sort() or shuffle() or whatever), which specify what range of a container you want to sort or shuffle or whatever. The only trick is to remember that the element pointed to by the second parameter is not included in the sorting or shuffling, this is because of the half-open range pattern that you're familiar with from doing for loops in CSCI 40.
Категория
Язык программирования C++
Комментариев нет.