Slicing a vector in C++

后端 未结 4 476
执念已碎
执念已碎 2020-12-29 01:54

Is there an equivalent of list slicing [1:] from Python in C++ with vectors? I simply want to get all but the first element from a vector.

Python\'s lis

相关标签:
4条回答
  • 2020-12-29 02:39

    It seems that the cheapest way is to use pointer to the starting element and the number of elements in the slice. It would not be a real vector but it will be good enough for many uses.

    0 讨论(0)
  • 2020-12-29 02:40

    This can easily be done using std::vector's copy constructor:

    v2 = std::vector<int>(v1.begin() + 1, v1.end());
    
    0 讨论(0)
  • 2020-12-29 02:40

    You can follow the above answer. It's always better to know multiple ways.

    int main
    {
        std::vector<int> v1 = {1, 2, 3};
        std::vector<int> v2{v1};
        v2.erase( v2.begin() );
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-29 02:50

    I know it's late but have a look at valarray and its slices. If you are using a vector of some sort of NumericType, then it's worth giving it a try.

    0 讨论(0)
提交回复
热议问题