如何将指针(或引用)存储到std :: set中的对象

mic*_*c_e 5 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);
}
Run Code Online (Sandbox Code Playgroud)

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

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; }
               ~~~ ^ ~~~
Run Code Online (Sandbox Code Playgroud)

(gcc错误类似,但更长)

jua*_*nza 6

您需要使less-than运算符成为非成员,并为其提供const引用参数:

struct T {
    int val;
};

bool operator <(const T& lhs, const T& rhs) {
    return (lhs.val < rhs.val);
}
Run Code Online (Sandbox Code Playgroud)

这允许隐式转换来自std::reference_wrapper<T>T两个LHS和RHS的<操作者,而构件版本只允许在RHS的隐式转换.LHS和二元运算符的RHS之间的对称性是将它们作为非成员实现的经典论据之一.