在 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/