Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

arrays

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.

like image 835
Nicholas Hazen Avatar asked Nov 27 '12 01:11

Nicholas Hazen


People also ask

How do I return a sub array?

slice() The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified. Basically, slice lets you select a subarray from an array.

Can you equate arrays in C?

You need to loop. These are essentially fixed pointers, so you can't just assign one to another. You have to copy each value.


2 Answers

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.

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.

like image 58
Dietrich Epp Avatar answered Oct 06 '22 00:10

Dietrich Epp


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

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
like image 41
raj kumar Avatar answered Oct 06 '22 00:10

raj kumar