Let_Me_Be Let_Me_Be - 3 days ago 5
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
std::map
to store the structure and search by ID, but I searching for a way to achieve the same thing with a
std::set
(since I don't really need to separate the ID and the structure).

std::set::find
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

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.

Comments