本文作者原创,首发在本博客;CSDN 上的同名文章已标注为转载并回链到本页:https://blog.csdn.net/qq_30220519/article/details/139184128
#include
class Base;
using BaseSp = std::shared_ptr
class Base
{
public:
explicit Base(int id) : ID(id) {}
int ID;
};
class Sorter
{
public:
virtual bool sort(const BaseSp &l, const BaseSp &r) { return true; }
};
using SorterSp = std::shared_ptr
class BaseNameSorter : public Sorter
{
public:
bool sort(const BaseSp &l, const BaseSp &r) override { return l->ID < r->ID; }
};
using BaseNameSorterSp = std::shared_ptr
class BaseDateSorter : public Sorter
{
public:
bool sort(const BaseSp &l, const BaseSp &r) override { return l->ID < r->ID; }
};
using BaseDateSorterSp = std::shared_ptr
class ShareSorter
{
public:
SorterSp sorter;
};
using ShareSorterSp = std::shared_ptr
using ShareSorterWp = std::weak_ptr
class SortBase
{
public:
explicit SortBase(BaseSp data, ShareSorterSp sorter) : base(data), m_sortDelegate(sorter) {}
bool operator<(const SortBase &other) const
{
bool isExpired = m_sortDelegate.expired();
auto delegate = m_sortDelegate.lock();
if (isExpired || !delegate || !delegate->sorter) {
assert(false);
return true;
}
return delegate->sorter->sort(base, other.base);
}
BaseSp base;
ShareSorterWp m_sortDelegate;
};
class Group
{
public:
std::set
ShareSorterSp m_sorter;
};
int main()
{
Group styleGroups; //数组组
ShareSorterSp shareSorter = std::make_shared
shareSorter->sorter = std::make_shared
styleGroups.m_sorter = shareSorter; //初始化组与子共享排序器
BaseSp base1 = std::make_shared
BaseSp base2 = std::make_shared
styleGroups.m_set.emplace(base1, styleGroups.m_sorter); //添加待排序数据
styleGroups.m_set.emplace(base2, styleGroups.m_sorter); //触发共享排序器
shareSorter->sorter = std::make_shared
BaseSp base3 = std::make_shared
styleGroups.m_set.emplace(base3, styleGroups.m_sorter);
return 0;
}