c++ - 如何在 std::set 中存储指向对象的指针(或引用)

标签 c++ stl

在 C++11 STL 中是否有适当的方法将对象指针存储在 std::set 中? , 并让它们按对象的 operator < 正确排序方法?

当然,我也可以自己编写 Compare输入并将其传递给 set作为它的第二个模板参数,但我想 STL 会提供一种更方便的方法。

谷歌搜索显示 std::reference_wrapper ,在我看来应该允许这样的代码:

#include <functional>
#include <set>

struct T {
    int val;
    bool operator <(T& other) {
        return (this->val < other.val);
    }
};

int main() {
    std::set<std::reference_wrapper<T>> s;
    T a{5};
    s.insert(a);
}

但实际上,这会导致编译错误:

clang++ -std=c++11 -Wall -Wextra -pedantic test.cpp -o test
In file included from test.cpp:1:
In file included from /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../include/c++/4.8.2/functional:49:
/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../include/c++/4.8.2/bits/stl_function.h:235:20: error: invalid operands to binary expression ('const std::reference_wrapper<T>'
      and 'const std::reference_wrapper<T>')
      { return __x < __y; }
               ~~~ ^ ~~~

(gcc错误类似,但长很多)

最佳答案

你需要让你的小于运算符成为非成员,并给它 const引用参数:

struct T {
    int val;
};

bool operator <(const T& lhs, const T& rhs) {
    return (lhs.val < rhs.val);
}

这允许从 std::reference_wrapper<T> 进行隐式转换至 T< 的 LHS 和 RHS 上运算符,而成员版本只允许在 RHS 上进行隐式转换。二元运算符的 LHS 和 RHS 之间的对称性是将它们实现为非成员的经典论据之一。

关于c++ - 如何在 std::set 中存储指向对象的指针(或引用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21488844/

相关文章:

C++ std::deque 实现:为什么不使用循环缓冲区?

c++ - vector 未显示正确的元素

c++ - 最小的 C++ STL vector 实现问题

c++ - std::normal_distribution 的类型取决于模板

c++ - 处理 MPI 应用程序中的信号/正常退出

c++ - "Missing type specifier int assumed"C++ 问题

c++ - 适合 BitTorrent 客户端的多线程模型?

c++ - 调用 get() 后 std::future 仍然有效(抛出异常)

c++ - 返回指向私有(private)成员的指针的公共(public)方法的单元测试

c++ - 我不明白的关于默认构造函数的一些事情