简体   繁体   English

从C ++中的vector <int>生成一个subList

[英]Producing a subList from a vector<int> in C++

is there a built-in STL method to do that? 是否有内置的STL方法来做到这一点?

In java, there is list.subList(a,b) for extracting [a,b). 在java中,有list.subList(a,b)用于提取[a,b)。 Similar method in STL C++? STL C ++中的类似方法?

当然。

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 . 这将复制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. 这样可以避免复制。

当然。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM