STL map - Can I find() on a subset of key

T

thotashireesh

Hi All,

I am using a stl::map and my key is a structure which looks like

struct key
{
int id;
char* name;
};

struct data
{..
....
};

typedef std::map<key*,data*,compare> table;
//compare is defined too

Most of the times, I require a find(key*) and that works fine. But on a
few occasions I need to do find(name)[purpose is to check if there is
atleast one entry with that name]. This fails as my library [windriver]
seems to be creating only find(const key*) and find(const key*) const !

Is there any roundabout way or should I do a brute checking (linear
check) ?

Thanks for your time,

Shireesh
 
M

Marcin Kalicinski

I am using a stl::map and my key is a structure which looks like
struct key
{
int id;
char* name;
};

struct data

typedef std::map<key*,data*,compare> table;
//compare is defined too

Most of the times, I require a find(key*) and that works fine. But on a
few occasions I need to do find(name)[purpose is to check if there is
atleast one entry with that name]. This fails as my library [windriver]
seems to be creating only find(const key*) and find(const key*) const !

You can only search a map efficiently with the comparison function it was
defined with. The reason is that map builds an internal structure optimized
for such a search. If you want to search with another criteria, linear
search is the best you can get.

What you might do is to create a second map, such as this:

map<key *, data *, different_compare>

and put the same keys and data there. Then you can search it with different
criteria.

If you only want to check if there is at least one entry with that name (as
you write), you might also use a set for that purpose, because you don't
need access to the data:

set<key *, different_compare>

cheers,
M.
 
M

Marcin Kaliciñski

If you only want to check if there is at least one entry with that name
(as you write), you might also use a set for that purpose, because you
don't need access to the data:

set<key *, different_compare>

Actually it should be multiset, because it seems that you can have more than
one entry with the same name:

multiset<key *, different_compare>

cheers,
M.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top