My teacher for an assignment problems requires that we pass an array to a function that just finds the median of it. and if there's an even amount of numbers, it averages the two in the middle. I quote from him "use pointers whenever possible". The only one I could see using a pointer is the array itself?
I understand the concept of what needs to happen, I'm just not sure how to properly use pointers and Googling doesn't reveal too helpful results.
int medianArray(int *pArray, int sizeArray)
{
if(sizeArray % 2 == 1)
{
return (pArray[((int)(sizeArray/2)) -1 ] + pArray[((int)(sizeArray/2)) +1 ]) / 2;
}
else
return pArray[(int) sizeArray/2];
}
You've got the right idea here, but you're computing your offsets wrong.
Here's an idea:
size_t median = sizeArray / 2;
return (pArray[median] + pArray[median+1]) / 2;
Don't forget this will fail if the values exceed int
bounds, and additionally you should be using size_t
to express sizes as that should never be negative.
Additionally, there's no point in casting the result of an int
calculation to int.
Regarding this C++ lesson, I think anything that bucks the principles laid out in the Standard Library better have a good reason for doing so. While an academic exploration of the benefits of pointers vs. iterators vs. references is always encouraged, advocating pointers "whenever possible" is a bad plan and comes from a C mindset.
In a modern C++ course this assignment would revolve around computing the median of an unsorted Standard Library container of an arbitrary type by defining a template function.
just so you can get a concrete feel regarding what people were talking about when they said 'modern c++ doesnt use pointer' etc.
One alternative is to use std::vector
int medianArray(const std::vector<int> &vec)
{
int sizeArray = vec.size();
if(sizeArray % 2 == 1)
{
return (vec[((int)(sizeArray/2)) -1 ] + vec[((int)(sizeArray/2)) +1 ]) / 2;
}
else
return vec[(int) sizeArray/2];
}
note that vector knows how big it is. It also wont run off either end if you use vec.at(index)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.