Slicing a vector

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

    use boost range adapters. they are lazy:

    operator|() is used to add new behaviour lazily and never modifies its left argument.

    boost::for_each(v|sliced(1,5)|transformed(doSomething));
    

    doSomething needs to take range as input. a simple (may be lambda) wrapper would fix that.

    0 讨论(0)
  • 2020-12-14 02:04

    Taken from here:

    std::vector<myvector::value_type>(myvector.begin()+start, myvector.begin()+end).swap(myvector);
    

    Usage example:

    #include <iostream>
    #include <vector>
    
    int main ()
    {
        std::vector<int> indexes{3, 6, 9};
    
        for( auto index : indexes )
        {
            int slice = 3;
            std::vector<int> bar{1, 2, 3, 4, 5, 6, 7, 8, 9};
            std::vector<int>( bar.begin() + index - slice, bar.begin() + index ).swap(bar);
    
            std::cout << "bar index " << index << " contains:";
            for (unsigned i=0; i<bar.size(); i++)
                std::cout << ' ' << bar[i];
            std::cout << '\n';
        }
    
        return 0;
    }
    

    Outputs:

    bar index 3 contains: 1 2 3
    bar index 6 contains: 4 5 6
    bar index 9 contains: 7 8 9
    
    0 讨论(0)
提交回复
热议问题