• we always use iterators to subscript, rather than [] operator. Because all of the library containers have iterators, but subscript operator is not.
  • begin回第一个元素,end回最后一个的后一个位置。也就是当begin==end的时候其实就代表已经到尽头了

Types

Library types that have iterators define two types: iterator and const_iterator.

const_iterator behaves like a pointer to const.

Operators

迭代器不是指针,但是表现的像个指针,重载了很多指针的操作。 先有指针后有迭代器

*iter          // returns reference to the element
iter->mem      // dereference the iter and fetch the member
++iter         // increments iter to refer to next element
--iter         // decrements iter to refer to previous element
iter1 == iter2 // 
iter ± n       // yields a iterator to n elements forward (backward)
iter1 - iter2  // 得数,1加多少到2的数;is a signed integral type named difference_type
>, >=, <, <=   // 位置先后

use != rather <

由于 iterator 通常没有关系运算符,所以通常使用不等于来作为循环的条件

Functions

/* begin, end; cbegin, cend */
vector<int> v;
const vector<int> cv;
auto it1 = v.begin();  // it1 has type vector<int>::iterator
auto it2 = cv.begin(); // it2 has type vector<int>::const_iterator
auto it3 = v.cbegin(); // it3 also has type vector<int>::const_iterator