**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?

So I know that I need to sort the vector in order to find the median-- You don't need to call`std::sort`

. Use std::nth_element (see example) – PaulMcKenzie Apr 20 at 20:33`std::nth_element`

still changes the vector. Probably the simple approach would be to copy the vector locally and use`nth_element`

on that to return the median. No state change and`const`

is enforced. – doug Apr 20 at 20:52`mean`

posted by OP. That question was answered by a user and discussed in comments. After a day, the question was totally modified to calculate the median and then subsequently deleted. Now a new question has been posted which is exactly the same as the modified question. I recommend asking separate questions and not deleting original posts. Thank you! – Mukul Gupta Apr 20 at 20:53