如何确保自定义数据的boost :: unordered_set中没有重复项

时间:2015-02-16 10:52:22

标签: c++ boost stdset boost-unordered

我需要我的容器只包含唯一的元素,所以我有这样的结构:

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()超载会毫无用处。

1 个答案:

答案 0 :(得分:0)

以下是为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';
}

看到它运行here

相关问题