如何确保自定义数据的boost::unorderede_set中没有重复
How to ensure no duplicates in boost::unordered_set of custom data
我需要我的容器只包含唯一的元素,所以我有一个这样的结构:
class OD
{
private:
std::string key;
public:
OD(){}
OD(const WayPoint &origin, const WayPoint &destination):
origin(origin), destination(destination)
{
std::stringstream str("");
str << origin.node_->getID() << "," << destination.node_->getID();
key = str.str();
}
bool operator<(const OD & rhs) const
{
return key < rhs.key;
}
bool operator()(const OD & rhs, const OD & lhs)
{
return rhs < lhs;
}
};
和一个容器:
std::set<OD,OD> t;
现在我需要将容器更改为boost::unordered_set
类型,我需要修改函子吗?我很困惑,因为我知道我不能将订单和唯一性实现分开,而这次容器没有被订购。所以我担心我的operator()
过载将毫无用处。
以下是为unordered_set
:定义自定义哈希和比较运算符的示例
#include <iostream>
#include <functional>
#include <unordered_set>
struct X
{
std::string key_;
};
int main() {
std::unordered_set<X,
std::function<size_t(const X&)>,
std::function<bool(const X&, const X&)> > s{
5, // initial bucket count
[](const X& x) { return std::hash<decltype(x.key_)>()(x.key_); },
[](const X& lhs, const X& rhs) { return lhs.key_ == rhs.key_; }
};
s.insert({"one"});
s.insert({"two"});
s.insert({"three"});
for (auto& x : s)
std::cout << x.key_ << 'n';
}
看到它在这里运行。
相关文章:
- 为什么我无法更改"set<set>"循环中的值<int>
- 对于set上的循环-获取next元素迭代器
- 在声明中合并两个常量"std::set"(不是在运行时)
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将 std::set 与基于键的比较器一起使用
- 如何使用set实现无序数据结构?
- 使用运算符调用 void 函数时出错<set>
- 修改"std::set"中用户定义类型的值
- 生成提升::hana::set 的常量表达式问题
- 如何在构造函数参数中初始化"std::set"?
- 如何使用 lower_bound/upper_bound 从 std::set 获取索引号?
- 如何在 C++ 中转发声明 std::set?
- 重构使用动态强制转换的 std::set 的比较运算符
- set::find 查找不存在的元素
- 为什么 std::set.erase(first, last) 会影响从中获取 (first, last) 的容器?
- 将 std:set<int32_t> 复制到 std::set <uint32_t>的好方法
- 错误 C2676:std::set::const_iterator 没有运算符 + 函数?
- std::set 是否将对象连续存储在内存中?
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- google test PrintTo for std::set<std::string>