Slicing a vector

后端 未结 8 1980
伪装坚强ぢ
伪装坚强ぢ 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:52

    I learnt Python before I learnt C++. I wondered if C++ offered slicing of vectors like slicing in Python lists. Took a couple of minutes to write this function that allows you to slice a vector analogous to the way its done in Python.

    vector slice(const vector& v, int start=0, int end=-1) {
        int oldlen = v.size();
        int newlen;
    
        if (end == -1 or end >= oldlen){
            newlen = oldlen-start;
        } else {
            newlen = end-start;
        }
    
        vector nv(newlen);
    
        for (int i=0; i

    Usage:

    vector newvector = slice(vector_variable, start_index, end_index);
    

    The start_index element will be included in the slice, whereas the end_index will not be included.

    Example:

    For a vector v1 like {1,3,5,7,9}

    slice(v1,2,4) returns {5,7}

提交回复
热议问题