7

我有which 如果我从tostd::multiset迭代,我将得到排序的元素。除了从到迭代之外,我如何获得中间元素std::multiset::begin()std::multiset::end()std::multisetstd::multiset::begin()std::multiset::begin() + size() / 2

4

1 回答 1

10

这是获得 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;
}

如果您需要中值绝对偏差 (mdev),例如:

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);
}
于 2015-06-05T15:37:50.507 回答