我有一个具有唯一键的结构.我想将这些结构的实例插入到集合中.我知道要做到这一点,<运算符必须重载,以便set可以进行比较以进行插入.
以下不起作用:
#include <iostream>
#include <set>
using namespace std;
struct foo
{
int key;
};
bool operator<(const foo& lhs, const foo& rhs)
{
return lhs.key < rhs.key;
}
set<foo> bar;
int main()
{
foo *test = new foo;
test->key = 0;
bar.insert(test);
}
Run Code Online (Sandbox Code Playgroud)
ere*_*eOn 19
这可能有所帮助:
struct foo
{
int key;
};
inline bool operator<(const foo& lhs, const foo& rhs)
{
return lhs.key < rhs.key;
}
Run Code Online (Sandbox Code Playgroud)
如果使用名称空间,最好operator<()在同一名称空间中声明该函数.
为了完整的编辑后的缘故,和其他人指出,您要添加foo*其中foo的预期.
如果你真的想对付的指针,可以包裹foo*成一个智能指针类(auto_ptr,shared_ptr,...).
但请注意,在这两种情况下,您都会失去operator<运行的重载的好处foo,而不是foo*.
struct Blah
{
int x;
};
bool operator<(const Blah &a, const Blah &b)
{
return a.x < b.x;
}
...
std::set<Blah> my_set;
Run Code Online (Sandbox Code Playgroud)
但是,operator<除非重载具有直觉意义,否则我不喜欢重载(说一个Blah“小于”另一个真的有意义Blah吗?)。如果没有,我通常提供一个自定义比较器函数:
bool compareBlahs(const Blah &a, const Blah &b)
{
return a.x < b.x;
}
...
std::set<Blah,compareBlahs> my_set;
Run Code Online (Sandbox Code Playgroud)
您也可以重载operator <类内部,
struct foo
{
int key;
bool operator < (const foo &other) const { return key < other.key; }
};
Run Code Online (Sandbox Code Playgroud)
在您的问题中,如果要set<foo> bar;用作声明,则应将值插入为,
bar.insert(*test);
Run Code Online (Sandbox Code Playgroud)
但这不是一个好主意,因为您正在制作冗余副本。
| 归档时间: |
|
| 查看次数: |
29207 次 |
| 最近记录: |