【发布时间】:2020-05-04 08:17:00
【问题描述】:
我与应该支持自定义比较操作的std::set 斗争。我的目标是能够仅使用 key 参数调用 find ,而无需先创建 set 类型的对象。像这样的:
#include <set>
#include <cstdint>
#include <vector>
class TestItem {
public:
std::uint64_t id; // key
std::vector<double> areas; // some other data
};
struct TestItemCompare {
bool operator()(const std::uint64_t& lhs, const std::uint64_t& rhs) {
return lhs < rhs;
}
bool operator()(const std::uint64_t& lhs, const TestItem& rhs) {
return lhs < rhs.id;
}
bool operator()(const TestItem& lhs, const std::uint64_t& rhs) {
return lhs.id < rhs;
}
bool operator()(const TestItem& lhs, const TestItem& rhs) {
return lhs.id < rhs.id;
}
};
int main() {
std::set<TestItem, TestItemCompare> store;
std::uint64_t id = 0;
TestItem t;
t.id = 0;
auto it1 = store.find(t); // compiles
auto it2 = store.find(id); // fails to compile
return 0;
}
我认为这是可能的......
【问题讨论】:
-
您确定不想改用
std::map吗? -
没有对您要求的支持仅在 C++20 中添加。为什么不简单地使用
std::map<int,std::vector<double>>?正如上面评论中所建议的那样。 -
@ALX23z 透明比较在 C++14 中,您是否在考虑无序容器的透明哈希?
-
关于 std::map 的优点。 set的优势是什么,真的吗?我认为它可能很有效,因为它不会复制密钥(我也需要数据结构中的密钥)。但在这种情况下,密钥并没有那么大。