c++ - 当元素被包裹在智能指针中时,std::set 是否仍然排序?

标签 c++ c++11

假设有一个重载的类 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;

最佳答案

实际上,这很微妙,但您只想向该代码添加自定义比较器。

您需要从这些选项中选择一个以使代码有意义:

  1. 使用 boost::ptr_multiset<Rectangle> (推荐)

  2. 使用 std::multiset<std::shared_ptr<const Rectangle>, YourCustomComparator>

否则,您将能够在键位于 map 内时修改它们(它们不会是 const ),这很糟糕,并且会导致您进入未定义的行为。

关于c++ - 当元素被包裹在智能指针中时,std::set 是否仍然排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18563508/

相关文章:

c++ - cppcheck 如何抑制内联不匹配抑制?

c++ - 使用 C++ 将数组的所有值与另一个数组的值进行比较

c++ - 错误: 'member' is private within this context - namespace

c++ - 为什么 unique_ptr 会重载 reset(pointer p = pointer()) 和 reset(nullptr_t)?

c++ - 只有 operator() 的结构和普通函数之间的实际区别

c++ - 我如何制作 lambda 函数的原型(prototype)?

c++ - OpenGL:一次只能有一个 FBO 工作

c++ - for 循环/for_each 的每次迭代都可以并行完成吗? (C++11)

c++ - 分配 vector 而不复制它们

c++ - 输入/输出文件(数独求解器)