Is there a way, in C++, to extract part of an array?
I have some array, and I want to extract part of it to use as a parameter for a function. But I would prefer to do this without using for loops or using more variables than the array itself. Something like array[3-5].
I am pretty sure I have worked with languages where you could do this using '-' or '~', I am just not sure if it's possible in C++. I imagine it could possibly be done with pointer somehow.
Extracting partial array from array
Started by ThemePark, Nov 30 2008 04:31 PM
8 replies to this topic
#1
Posted 30 November 2008 - 04:31 PM
|
|
|
#2
Posted 30 November 2008 - 05:53 PM
If you are dealing with an array that isn't specially terminated, such as null terminated char arrays, then you MUST pass the size of the array as a minimum requirement for any function. You will need three parameters: a pointer to the array, and a minimum and maximum index. If you use a vector, you will have more flexibility.
#3
Posted 30 November 2008 - 06:10 PM
So I would not be able to do something like func(array[3-5]), but would have put the part I want into a new array instead?
#4
Posted 30 November 2008 - 06:18 PM
When you pass an array to a function, you pass the entire array. You can instead do:
Func(array,3,5)
or you can copy a section of the array to array2 and call
Func(array2,3)
Func(array,3,5)
or you can copy a section of the array to array2 and call
Func(array2,3)
#5
Posted 01 December 2008 - 05:27 AM
At the very least you need a length parameter on top of the array. Then you can pass a slice of the array--by offsetting the pointer--and use the length to retrieve the rest of the elements:
#include <iostream>
using namespace std;
template <typename T>
void print_slice(T *a, int n)
{
while (--n >= 0)
cout << *a++ << '\n';
}
int main()
{
int a[] = {1, 2, 3, 4, 5};
print_slice(a + 2, 2);
}
But no, C++ doesn't directly support full slicing of arrays where you can say something like a[2..3] and get {3, 4} as a result.
#6
Posted 01 December 2008 - 05:41 AM
CPD, brackets are usually considered to represent inclusive points.
#7
Posted 01 December 2008 - 07:10 AM
As far as I know, array in C++ it's just a pointer to the first element. You can't even figure out it's size. The only thing you can do with it is to shift the pointer to the first element. So slicing can be done by shifting first element and adjusting the size.
---
---
Edited by WingedPanther, 01 December 2008 - 08:43 AM.
Double post
#8
Posted 01 December 2008 - 07:20 AM
Quote
CPD, brackets are usually considered to represent inclusive points.
Quote
So slicing can be done by shifting first element and adjusting the size.
#9
Posted 01 December 2008 - 08:40 AM
CPD said:
But no, C++ doesn't directly support full slicing of arrays where you can say something like a[2..3] and get {3, 4} as a result.
My point? You use brackets (in maths terms) and don't represent all inclusive points.


Sign In
Create Account


Back to top









