• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

How to make array functions in C++ ?

Hey guys,

Well, I'm having loads of free time to kill, so I'm solving algo problems. Right now am making some sorting algo. For that I need to make array functions.
That is, some function which can take array as input and then give array as output. How to go about doing this in c++ ?

If it helps, Iam working on las vegas algo, making quick sort. Why ? Cause I find the name to be very fancy !!

Regards,
Aditya.
 
Last edited:
void function(type *out, type *in);

Or if you allocate the output array inside the function:

type* function(type *in);

But as this is C++, don't forget to delete the array later.
 
void function(type *out, type *in);

Or if you allocate the output array inside the function:

type* function(type *in);

But as this is C++, don't forget to delete the array later.

It depends on who creates the array, and if you care if the orginal array is lost.

You could just say

void sort(vartype* var)

and work with var as the array. var can be either on the stack or heap, it doesn't matter.

If you really want to return a copy of the array/pass in a copy, I would suggest using a vector instead.

vector<type> function(vector<type> thing);

That will work about like you would expect it.
 
As mentioned a lot depends with C++. The variable for an array is always a pointer, be it declared statically or dynamically. This means that you can pass an array very quickly, however the original data can be changed by the function (which is good if you are sorting "in place" using the same memory).

When you use the [] operation on a pointer, you essentially perform the following:

Code:
// Assuming array:
type var[10];
// The following are equivalent:
type a = var[4];
type b = *(var + 4);
type c = *((S*)((unsigned)var + 4*sizeof(type));

Assuming I typed that out right, a, b, and c should be equal. The point of b vs c is to show that when you do pointer arithmetic all incrementations are multiplied by the size of the pointer, so in c we cast to an unsigned integer first so that adding one actually increments the value as opposed to adding the size of the pointer's type.

Now the point of that explanation is to show how passing a pointer is the way you pass an array, and some of the common errors when working with pointers.
 
Back
Top