1 对于Vector,迭代器跟索引差别不大

for ( int i=0; i < vecVector.size(); i++ ){

..

}
for (auto iter = vecVector.begin(); iter != vecVector.end(); iter++){
 ...
}

但是,仅仅可以对支持 operator[](std::size_t)的容器使用索引

2 但是在vector中删除、插入元素,迭代器比索引更加方便

some_iterator = some_vector.begin();
while (some_iterator != some_vector.end()){
    if (/* some condition */)
    {
        some_iterator = some_vector.erase(some_iterator);
        // some_iterator now positioned at the element after the deleted element
    }
    else
    {
        if (/* some other condition */)
        {
            some_iterator = some_vector.insert(some_iterator, some_new_value);
            // some_iterator now positioned at new element
        }
        ++some_iterator;
    }}

3 迭代器让你的代码更加通用
比如:

typedef std::vector<int> Container ;

void doSomething(Container & p_aC){
    for(Container::iterator it = p_aC.begin(), itEnd = p_aC.end(); it != itEnd; ++it)
    {
       int & i = *it ; // i is now a reference to the value iterated
       // do something with "i"
    }}

如果,使用list替代上面的vector,那么迭代器的优势就显现出来了。

4 更重要的是,迭代器用于算法

copy(v.begin(), v.end(), l.begin());

for (auto it = v.begin(); it != v.end(); ++it) {
    // if the current index is needed:
    auto i = std::distance(v.begin(), it);

    // access element as *it

    // any code including continue, break, return}

5 迭代器更具有oop思想

6 模板编程

template <class Container>
double product( const Container & container )
{
  Container::iterator i = container.begin();
  double prod = 1;

  while ( i != container.end() ) prod *= *i++;

  return prod;
}

Iterators make your code more generic.

for_each + lambda

std::for_each(v.begin(), v.end(), [](T const& elem) {
     // if the current index is needed:
     auto i = &elem - &v[0];

     // cannot continue, break or return out of the loop});
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐