I have std::multiset
which If i iterate over from std::multiset::begin()
to std::multiset::end()
i will get sorted elements. How Do I get the middle element in this std::multiset
other than iterating from std::multiset::begin()
to std::multiset::begin() + size() / 2
size() / 2); int median = *it; If you want to include duplicates when considering the median you can use std::multiset ( {1, 2, 3, 3, 3, 3, 3, 3, 3} median's would be 3 ) : std::multiset<int>::iterator it = s.
The multiset::begin() is a built-in function in C++ STL that returns an iterator pointing to the first element in the multiset container. Since multiset always contains elements in an ordered way, begin() always points to the first element according to the sorting criterion.
Here is a solution to get median value for std::multiset:
template<class T>
double GetMedian(const std::multiset<T>& data)
{
if (data.empty())
throw std::length_error("Cannot calculate median value for empty dataset");
const size_t n = data.size();
double median = 0;
auto iter = data.cbegin();
std::advance(iter, n / 2);
// Middle or average of two middle values
if (n % 2 == 0)
{
const auto iter2 = iter--;
median = double(*iter + *iter2) / 2; // data[n/2 - 1] AND data[n/2]
}
else
{
median = *iter;
}
return median;
}
And if you need median absolute deviation (mdev) for example:
template<class T>
double GetMedianAbsoluteDeviation(const std::multiset<T>& data)
{
const double fMedian = GetMedian(data);
std::multiset<double> diff;
for (const auto& x : data)
{
diff.insert(std::abs(fMedian - x));
}
return GetMedian(diff);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With