如何在不复制的情况下stable_sort

How to stable_sort without copying?

本文关键字:情况下 stable sort 复制      更新时间:2023-10-16

为什么stable_sort需要一个复制构造函数?(swap应该就足够了,对吧?
或者更确切地说,如何在不复制任何元素的情况下stable_sort范围?

#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 中的讨论,因为我发现它很有趣,这里有一个解决方案,它只使用 swap 对原始向量进行排序(通过使用指针包装器对索引进行排序)。

编辑:这是解决方案v2,它就地交换。

编辑(通过OP):不需要C++11的STL友好版本。

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>()); }

我没有标准的副本。值得一提的是,这是2010年免费提供的草案中的措辞:

25.4.1.2 stable_sort

[...]

要求

:*优先的类型应满足可交换要求(表 37),可移动可构造要求(表 33)和可移动可分配要求(表 35)。

使用最新的 Visual C++进行测试,它确实允许在定义移动构造函数但复制构造函数是私有构造函数时进行排序。

所以回答你的问题:你不走运。使用 std::stable_sort 以外的内容或使用包装类。