C++ 中有没有办法从数组中获取子数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13576160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:30:22  来源:igfitidea点击:

Is there a way in C++ to get a sub array from an array?

c++arrays

提问by Nicholas Hazen

I'm having a brain fart at the moment and I am looking for a fast way to take an array and pass half of it to a function. If I had an array A of ten elements, in some languages I could pass something like A[5:] to the function and be done with it. Is there a similar construct in c++? Obviously I'd like to avoid and sort of looping function.

我现在脑子里放屁了,我正在寻找一种快速的方法来获取一个数组并将它的一半传递给一个函数。如果我有一个由十个元素组成的数组 A,在某些语言中,我可以将类似 A[5:] 之类的东西传递给函数并完成它。C++ 中是否有类似的结构?显然我想避免和某种循环功能。

采纳答案by Dietrich Epp

Yes. In plain C you use pointers, but in C++ you can use any kind of iterator (a pointer can be considered an iterator).

是的。在普通 C 中,您使用指针,但在 C++ 中,您可以使用任何类型的迭代器(指针可以被视为迭代器)。

template<typename Iter>
void func(Iter arr, size_t len) { ... }

int main() {
    int arr[10];
    func(arr, 10);    // whole array
    func(arr, 5);     // first five elements
    func(arr + 5, 5); // last five elements

    std::vector<Thing> vec = ...;
    func(vec.begin(), vec.size());          // All elements
    func(vec.begin(), 5);                   // first five
    func(vec.begin() + 5, vec.size() - 5);  // all but first 5

    return 0;
}

The typical trick is to pass a pointer to the first element of the array, and then use a separate argument to pass the length of the array. Unfortunately there are no bounds checks, so you have to be careful to get it right or you will scribble on your memory.

典型的技巧是传递一个指向数组第一个元素的指针,然后使用一个单独的参数来传递数组的长度。不幸的是,没有边界检查,所以你必须小心做对,否则你会在你的记忆中乱涂乱画。

You can also use half-open ranges. This is the most common way to do it. Many functions in the standard library (like std::sort) work this way.

您也可以使用半开范围。这是最常见的方法。标准库中的许多函数(如std::sort)以这种方式工作。

template<class Iter>
void func(Iter start, Iter end) { ... }

int main() {
    int arr[10];
    func(arr, arr + 10);       // whole array
    func(arr, arr + 5);        // first five elements
    func(arr + 5, arr + 10);   // last five elements

    std::vector<Thing> vec = ...;
    func(vec.begin(), vec.end());       // whole vector
    func(vec.begin(), vec.begin() + 5); // first five elements
    func(vec.begin() + 5, vec.end());   // all but the first five elements

    return 0;
}

Again, no bounds checks.

同样,没有边界检查。

回答by raj kumar

i also had the same use but instead i used vector and used the syntax

我也有同样的用法,但我使用了 vector 并使用了语法

vector <int> a(10);
// for example to use by removing first element

a = std::vector<int>(a.begin() + 1, a.end())
//its ur turn to change the size