Skipping in Range-based for based on 'index'?

后端 未结 7 1433
一向
一向 2021-01-02 01:10

Is there a way to access the iterator (suppose there\'s no loop index..?) in a C++11 range-based for loop?

Often we need to do something special with the fi

7条回答
  •  情书的邮戳
    2021-01-02 02:07

    When I need to do something like this on a random access container, my habit is to iterate over the indexes.

    for( std::size_t i : indexes( container ) ) {
      if (i==0) continue;
      auto&& e = container[i];
      // code
    }
    

    the only tricky part is writing indexes, which returns a range of what boost calls counting iterators. Creating a basic iterable range from iterators is easy: either use boost's range concept, or roll your own.

    A basic range for an arbitrary iterator type is:

    template
    struct Range {
      Iterator b; Iterator e;
      Range( Iterator b_, Iterator e_ ):b(b_), e(e_) {};
      Iterator begin() const { return b; }
      Iterator end() const { return e; }
    };
    

    which you can gussy up a bunch, but that is the core.

提交回复
热议问题