本文介绍了如何stable_sort没有复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 stable_sort 需要一个复制构造函数? ( swap 应该足够了吗?)

或者,我如何 stable_sort 没有复制任何元素?

Why does stable_sort need a copy constructor? (swap should suffice, right?)
Or rather, how do I stable_sort a range without copying any elements?

#include <algorithm>

class Person
{
    Person(Person const &);  // Disable copying
public:
    Person() : age(0) { }
    int age;
    void swap(Person &other) { using std::swap; swap(this->age, other.age); }
    friend void swap(Person &a, Person &b) { a.swap(b); }
    bool operator <(Person const &other) const { return this->age < other.age; }
};

int main()
{
    static size_t const n = 10;
    Person people[n];
    std::stable_sort(people, people + n);
}


推荐答案

OP,因为我发现它很有趣,这里有一个解决方案,它只使用交换排序原始向量(通过使用指针包装来排序索引)。

Expanding upon the discussion in the OP, and because I found it interesting, here's a solution which uses only swap to sort the original vector (by using a pointer wrapper to sort indices).

编辑:

编辑(由OP):一个STL友好的版本,不需要C ++ 11。

Edit (by OP): An STL-friendly version which doesn't require C++11.

template<class Pred>
struct swapping_stable_sort_pred
{
    Pred pred;
    swapping_stable_sort_pred(Pred const &pred) : pred(pred) { }

    template<class It>
    bool operator()(
        std::pair<It, typename std::iterator_traits<It>::difference_type> const &a,
        std::pair<It, typename std::iterator_traits<It>::difference_type> const &b) const
    {
        bool less = this->pred(*a.first, *b.first);
        if (!less)
        {
            bool const greater = this->pred(*b.first, *a.first);
            if (!greater) { less = a.second < b.second; }
        }
        return less;
    }
};

template<class It, class Pred>
void swapping_stable_sort(It const begin, It const end, Pred const pred)
{
    typedef std::pair<It, typename std::iterator_traits<It>::difference_type> Pair;
    std::vector<Pair> vp;
    vp.reserve(static_cast<size_t>(std::distance(begin, end)));
    for (It it = begin; it != end; ++it)
    { vp.push_back(std::make_pair(it, std::distance(begin, it))); }
    std::sort(vp.begin(), vp.end(), swapping_stable_sort_pred<Pred>(pred));
    std::vector<Pair *> vip(vp.size());
    for (size_t i = 0; i < vp.size(); i++)
    { vip[static_cast<size_t>(vp[i].second)] = &vp[i]; }

    for (size_t i = 0; i + 1 < vp.size(); i++)
    {
        typename std::iterator_traits<It>::difference_type &j = vp[i].second;
        using std::swap;
        swap(*(begin + static_cast<ptrdiff_t>(i)), *(begin + j));
        swap(j, vip[i]->second);
        swap(vip[j], vip[vip[j]->second]);
    }
}

template<class It>
void swapping_stable_sort(It const begin, It const end)
{ return swapping_stable_sort(begin, end, std::less<typename std::iterator_traits<It>::value_type>()); }

这篇关于如何stable_sort没有复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 23:28