Let_Me_Be Let_Me_Be - 1 year ago 73
C++ Question

Efective search in set with non-key type

I have a similar data structure like this:

struct Data { std::string id; Blob data; };

Now I can use a
to store the structure and search by ID, but I searching for a way to achieve the same thing with a
(since I don't really need to separate the ID and the structure).

of course takes the key type as a parameter, so I could do something like this (with the appropriate constructor):

set<Data> x; x.find(Data("some_id"));

But I would like to avoid this if possible. It would require having a constructor that allows ID without data, plus I don't really like constructing an object, just to use it as a key for search.

So my question is: Is there a better way?

Answer Source

Unless the overhead is demonstrably unacceptable I'd go for std::map<std::string, Data *>, or possibly std::map<std::string, boost::shared_ptr<Data> >, assuming you don't have access to a compiler that provides shared_ptr natively.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download