0

I need my container to contain unique elements only, so I have a structure like this:

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

and a container :

std::set<OD,OD> t;

now I need to change my container to boost::unordered_set type, do I need to modify the functor? I am confused because I know I can't separate order and uniqueness implementation and this time the container is not ordered . So I fear my operator() overload would be useless.

rahman
  • 4,820
  • 16
  • 52
  • 86
  • 3
    The default comparator for `set` (`std::less`) already defers to the `<` operator; no need to make a custom one. For `unordered_set` you need a hash and a `==` operator. – T.C. Feb 16 '15 at 10:55
  • The answer [here](http://stackoverflow.com/questions/6687162/c-some-questions-on-boostunordered-map-boosthash?rq=1) communicates what's needed. – Tony Delroy Feb 16 '15 at 11:18

1 Answers1

0

Here's an example of defining custom hash and comparison operators for an 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';
}

See it run here.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252