Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::multiset and finding the middle element

Tags:

c++

stl

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

like image 949
Avinash Avatar asked Aug 27 '12 10:08

Avinash


People also ask

How do you find the median of a set in C++?

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.

How do I get the first element of a multiset?

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.


1 Answers

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);
}
like image 127
Sergey Avatar answered Oct 03 '22 06:10

Sergey