tags:

views:

351

answers:

3

I want to create a container which can associate a CLSID structure to something else (for example, a string); for example, std::map.

(the CLSID means standard Windows CLSID structure)

However when I want to use its find() and insert (object[clsid] = string), the STL just failed and gives errors.

Does anyone know how to solve this?

For example:

typedef std::map<CLSID, std::string> MyCLSIDMap;
MyCLSIDMap mymap;
CLSID sample = CLSID_NULL;

mymap[sample] = string("test");   // compilation failed here
+2  A: 

Does your CLSID structure support a usable operator<()? That's crucial for std::map (you can build it as a separate bool functor taking two const CLSID& arguments, it doesn't have to be a method operator<() in CLSID -- but then you'll have to say std::map and not just map ...!).

Alex Martelli
+3  A: 

As Alex has answered, std::map needs to compare it's keys with op<.

bool operator<(CLSID const& l, CLSID const& r)
{
    return memcmp(&l, &r, sizeof(CLSID)) < 0;
}
Simon Buchan
exactly what I need! thanks
A: 

To use an STL map where the keys are structures, you'll need to provide your own strict weak ordering function object:

struct CompareCLSID
{
  bool operator()(const CLSID &s1, const CLSID &s2) const
  {
    // returns true if s1 is less than s2
  }
};

and then your map's type would be map<CLSID, string, CompareCLSID>.

However, if you don't need your container is sorted (that's my guess), you should be using hash<> or hash_map<>. In that case, you'll have to provide your own hash function.

thesamet
Just defining an operator< is enough in this case. Defining a simple function (bool CompareCLSID(...) {} is the same thing if you have no state) or function object is useful if you need to switch out the behavior.
Simon Buchan
I don't think you can pass a simple function to map. Can you give an example?defining operator<() will work, but I'd recommend against defining it in a public interface, if it's ad-hoc for the map and there isn't a lot of meaning in comparing those objects.
thesamet
This will look dumb in a comment: "typedef std::map<CLSID, std::string, bool(*)(CLSID constmap_t map("
Simon Buchan