假设有一个重载的类 operator<
...
class Rectangle {
// ...
const inline bool operator< (const Rectangle &rhs) const {
return x < rhs.x || (x == rhs.x && y < rhs.y);
}
}
...做 set
当元素被包裹在一个智能指针中时仍然使用这个重载?
std::multiset<std::shared_ptr<Rectangle>> elements;
最佳答案
实际上,这很微妙,但您不只想向该代码添加自定义比较器。
您需要从这些选项中选择一个以使代码有意义:
使用
boost::ptr_multiset<Rectangle>
(推荐)使用
std::multiset<std::shared_ptr<const Rectangle>, YourCustomComparator>
否则,您将能够在键位于 map 内时修改它们(它们不会是 const
),这很糟糕,并且会导致您进入未定义的行为。
关于c++ - 当元素被包裹在智能指针中时,std::set 是否仍然排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18563508/