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



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

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';
}

看到它在这里运行。

最新更新