Slicing a vector

后端 未结 8 1974
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 01:12

I have a std::vector. I want to create iterators representing a slice of that vector. How do I do it? In pseudo C++:

class InterestingType;

void doSomethi         


        
8条回答
  •  死守一世寂寞
    2020-12-14 01:45

    You'd just use a pair of iterators:

    typedef std::vector::iterator vec_iter;
    
    void doSomething(vec_iter first, vec_iter last) {
        for (vec_iter cur = first; cur != last; ++cur) {
           std::cout << *cur << endl;
        }
    }
    
    int main() {
       std::vector v();
       for (int i= 0; i < 10; ++i) { v.push_back(i); }
    
       doSomething(v.begin() + 1, v.begin() + 5);
       doSomething(v.begin() + 2, v.begin() + 4);
       return 0;
    }
    

    Alternatively, the Boost.Range library should allow you to represent iterator pairs as a single object, but the above is the canonical way to do it.

提交回复
热议问题