使用 std::sort 对自定义类的智能指针进行排序
Sorting smartpointer of custom classes with std::sort
我遇到的问题是我有一个实现operator<
的自定义类的shared_ptr
向量。
在堆栈上使用类时,我可以使用 std::sort,而无需指定Compare
作为排序参数。但是,当然,当我使用shared_ptr
时(显然我认为)会尝试对指针进行排序,而不是对象本身。
我想知道是否可以在带有智能指针的容器上调用std::sort
,并且仍然可以调用实际对象的 Compare 运算符而不是指针,而无需提供第三个参数来"排序"。
为完整起见,MWE:
#include <vector>
#include <iostream>
#include <algorithm>
#include <memory>
class Date
{
public:
Date(int y, int m) : year(y), month(m) {}
bool operator<(const Date& rhs)
{
if (year > rhs.year) return false;
else if (year == rhs.year)
{
return month < rhs.month;
}
return true;
}
int year;
int month;
};
int main()
{
Date d1(1999,12);
Date d3(2000,10);
Date d2(2000,1);
Date d4(1997,9);
std::vector<std::shared_ptr<Date>> dates = {std::make_shared<Date>(d1), std::make_shared<Date>(d2), std::make_shared<Date>(d3), std::make_shared<Date>(d4)};
std::sort(dates.begin(), dates.end()); // doesn't work. orders by pointers
// std::sort(dates.begin(), dates.end(), [](std::shared_ptr<Date> d1, std::shared_ptr<Date> d2) { return *d1 < *d2; }); // this works
for (const auto& d : dates)
{
std::cout << d->year << " " << d->month << 'n';
}
return 0;
}
正如你所发现的,std::shared_ptr
的比较运算符使用它引用的指针。这样,2 个分配的实例比较相等,仍然比较为不相等。
使用函数显式排序是一件好事。
std::sort(dates.begin(), dates.end(), [](std::shared_ptr<Date> d1, std::shared_ptr<Date> d2) { return *d1 < *d2; });
但是,如果你必须在多个地方这样做,你可以将ptr包装在一个类/结构中:
template<typename T>
struct SharedPtr final
{
std::shared_ptr<T> ptr;
bool operator==(const T &rhs) const
{ return *ptr == rhs; }
bool operator==(const SharedPtr<T> &rhs) const
{ return *ptr == *rhs.ptr; }
// ...
};
随意使用 nullptr 检查、其他重载和运算符进行扩展<</p>
在您的情况下,需要提供第三个参数。但是,如果您要大量使用它,则可以通过创建一个重载的特殊结构来简化它operator()
class Date
{
public:
struct CompareSharedPtr
{
bool operator()(const std::shared_ptr<Date>& d1, const std::shared_ptr<Date>& d2)
{
return *d1 < *d2;
}
};
Date(int y, int m) : year(y), month(m) {}
bool operator<(const Date& rhs)
{
if (year > rhs.year) return false;
else if (year == rhs.year)
{
return month < rhs.month;
}
return true;
}
int year;
int month;
};
和用法
std::sort(dates.begin(), dates.end(), Date::CompareSharedPtr{});
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 优先顺序:智能指针和类析构函数
- 对于C++中使用智能指针的指针算术限制,有没有一种变通方法
- 智能指针作为无序映射键,并通过引用进行比较
- 智能指针概念所有权和寿命
- 正在理解智能指针,但出现错误:未分配正在释放的指针
- 尝试使用智能指针时引发异常
- 我可以制作指向智能指针的智能指针吗?
- 通过智能指针和转换对基本模板参数进行模板推导
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 从堆栈分配的原始指针构造智能指针
- 初始化指向类实例的智能指针并访问其方法
- 如何使用 std::make_shared 创建基类类型的智能指针?
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 编译器不会使用 -std=c++11 编译智能指针
- 具有智能指针的多态性
- C++:矢量分配器行为、内存分配和智能指针
- 通过简单的包装指针C++智能指针性能和差异
- 矢量中的自动指针(智能)
- Std::vector的对象/指针/智能指针传递对象(总线错误:10)