I've created a method called Collect that adds a bunch of values to a vector (shown below)
void Median::Collect(double datum)
{
myVector.push_back(datum);
}
I need to create a method that calculates the median of all of the values I collected in the vector in the method above. The function definition is written below
/* Calculates the median of the data (datum) from the Collect method.
*/
double Median::Calculate() const
{
}
So I know that I first need to sort the vector in order to find the median. Below is my attempt:
double Median::Calculate() const
{
std::sort(myVector.begin(), myVector.end());
double median;
if (myVector.size() % 2 == 0)
{// even
median = (myVector[myVector.size() / 2 - 1] + myVector[myVector.size() / 2]) / 2;
}
else
{// odd
median = myVector[myVector.size() / 2];
}
return median;
}
But I realized that this wasn't compiling because the method is const, so sorting the values of the vector would alter the vector, which isn't allowed in a const function. So what am I supposed to be doing for this method?