有没有C ++中的方式来获得数组的数组子? [英] Is there a way in C++ to get a sub array from an array?

查看:142
本文介绍了有没有C ++中的方式来获得数组的数组子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此刻大脑放屁,我要寻找一个快速的方式来采取一个数组并传递一半是给一个函数。如果我有十个元素的数组A,在某些语言中,我可以通过类似A [5:]的功能和与它做。有没有C ++中的类似的结构?很显然,我想避免和排序循环的功能。

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.

推荐答案

是的。在纯C,你使用指针,但在C ++中你可以使用任何类型的迭代器(一个指针可以被认为是一个迭代器)。

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

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.

您也可以使用半开放范围。这是为了做到这一点的最常见的方式。在标准库中的许多功能(如的std ::排序)以这种方式工作。

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.

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.

这篇关于有没有C ++中的方式来获得数组的数组子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆