在C ++中有一种方法从数组中获取子数组? [英] Is there a way in C++ to get a sub array from an array?

查看:2372
本文介绍了在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 :: sort )以这种方式工作。

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;
}

再没有边界检查。

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

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