Why use iterators

分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

                       

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

for ( int i=0; i < vecVector.size(); i++ ){..}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
for (auto iter = vecVector.begin(); iter != vecVector.end(); iter++){ ...}
  
  
  • 1
  • 2
  • 3

但是,仅仅可以对支持 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;    }}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

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"    }}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

如果,使用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}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

5 迭代器更具有oop思想

6 模板编程

template <class Container>double product( const Container & container ){  Container::iterator i = container.begin();  double prod = 1while ( i != container.end() ) prod *= *i++;  return prod;}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

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});
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
           

分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值