开发者

Producing a subList from a vector<int> in C++

is there a built-in STL method to do开发者_如何转开发 that?

In java, there is list.subList(a,b) for extracting [a,b). Similar method in STL C++?


Sure.

std::vector<int> subList(&originalVector[a], &originalVector[b]);


You can do:

#include <vector>
#include <cassert>

int main() {
    std::vector<int> x;

    for (int i=0; i<10; ++i) {
        x.push_back(i);
    }

    // Here we create a copy of a subsequence/sublist of x:
    std::vector<int> slice_of_x(x.begin() + 3, x.begin() + 7);

    assert(slice_of_x.size() == 7-3);
    assert(slice_of_x[0] == 3);

    return 0;
}

This will make a copy of the requested part of x. If you don't need a copy and would like to be more efficient, it might be preferable to pass around iterator (or pointer) pairs. That would avoid copying.


Sure.

std::vector<int> subList(originalVector.begin() + a, originalVector.begin() + b);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜