0

I am trying to create a unordered_set of list of string.

But I am stuck with this error:

/usr/include/c++/4.8/bits/hashtable_policy.h:1103:22: error: no match for call to ‘(const std::hash<std::list<std::basic_string<char> > >) (const std::list<std::basic_string<char> >&)’

I suspect, this is because STL doesn't have a hash function for list of string.

Creating a set of the same type works, but I am worried about efficiency issues (insertion and look up times).

Is there any workaround for this? I don't want to implement a hash function for lists! But may be someone can suggest me some alternative ideas.

Saswat Padhi
  • 4,614
  • 3
  • 16
  • 24
  • 2
    There is no hash function defined, as you say. So you don't want to fix the problem by defining a hash function, and you don't want to use a container that doesn't require one. Well, um, you just ruled out both your options for no reason :) – Lightness Races in Orbit Jan 16 '14 at 13:08
  • 1
    [Boost](http://www.boost.org/doc/libs/1_55_0/doc/html/hash.html)'s has support for the standard containers. – chris Jan 16 '14 at 13:12
  • 1
    "I don't want to implement a hash function for lists!" why not? It doesn't have to be particularly complicated. See http://www.boost.org/doc/libs/1_35_0/doc/html/hash/combine.html. If you don't want a boost dependency the implementation of `hash_combine` is not long. – Steve Jessop Jan 16 '14 at 13:14
  • In the worst case, I'll have to go with a `set`. I can't think of a good hash function for a `list` of `string`. – Saswat Padhi Jan 16 '14 at 13:14
  • Thanks chris and Steve :) – Saswat Padhi Jan 16 '14 at 13:15
  • 1
    This [answer](http://stackoverflow.com/a/19740245) might help you. – Daniel Frey Jan 16 '14 at 13:34
  • That's perfect Daniel! Thanks :) – Saswat Padhi Jan 16 '14 at 13:37

1 Answers1

0
class MyClass {
private:
    struct Hash : public std::unary_function< std::list<std::string> const& ls, 
                                                                       size_t> {
        std::size_t operator()(std::list<std::string> const& ls) const;
    };
typedef boost::unordered_set< std::list<std::string>, Hash > MyClassSet;
MyClassSet set_;
};

std::size_t MyClass::Hash::operator()(std::list<std::string> const& ls) const {
    std::size_t seed = 0;
    std::list<std::string>::iterator it = ls.begin();
    while ( it != ls.end()) {
      boost::hash_combine(seed, *it);
      ++it;
    }
    return seed;
}
4pie0
  • 27,469
  • 7
  • 70
  • 110