Boost logo

Boost Users :

Subject: Re: [Boost-users] [Unordered] template find() request
From: joaquin_at_[hidden]
Date: 2009-03-09 04:29:20


Daniel James escribió:
> 2009/3/9 <joaquin_at_[hidden]>:
>
>> FWIW, Boost.MultiIndex hashed indices do have a notion of "compatible keys"
>> allowing for
>> such heterogeneous lookup operations:
>>
>> http://www.boost.org/libs/multi_index/doc/tutorial/indices.html#hash_lookup
>> http://www.boost.org/libs/multi_index/doc/reference/hash_indices.html#lookup
>>
>
> In the equivalent to this case:
>
> boost::unordered_set<std::string> set;
>
> // ....
>
> set.find("x");
>
> Is a std::string constructed for every hash and equality call? I can't
> see a way to avoid that without introducing a traits class.
>

Translating the compatible key functionality of B.MI to the syntax of
boost::unordered_set,
you'd have two ways of doing this:

#1
  struct custom_hash:boost::hash<std::string>
  {
    using boost::hash<std::string>::operator();

    std::size_t operator()(const char* x)const
    {
      return boost::hash_range(x,x+std::strlen(x));
    }
  };

  struct custom_equal_to:std::equal_to<std::string>
  {
    using std::equal_to<std::string>::operator();

    bool operator()(const std::string& x,const char* y)const
    {
      return x==y;
    }
    bool operator()(const char* x,const std::string& y)const
    {
      return x==y;
    }
  };

  //...

  boost::unordered_set<std::string,custom_hash,custom_equal_to> set;

  //...

  set.find("x");

#2
  struct custom_hash
  {
    std::size_t operator()(const char* x)const
    {
      return boost::hash_range(x,x+std::strlen(x));
    }
  };

  struct custom_equal_to
  {
    bool operator()(const std::string& x,const char* y)const
    {
      return x==y;
    }
    bool operator()(const char* x,const std::string& y)const
    {
      return x==y;
    }
  };

  //...

  boost::unordered_set<std::string> set;

  //...

  set.find("x",custom_hash(),custom_equal_to());

Joaquín M López Muñoz
Telefónica, Investigación y Desarrollo


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net