finding/counting elements in a STL::map

M

Michael H Lees

Hi all,

As I see it there are two options for checking if for an element with
key 'x' exists in a map m....

1.) if(m.find(x)!=m.end())

or

2.) if(m.count(x))


They both take O(log N) where N is number of elements. Obviously they
both provide different things but which method should you use for just
checking if a key exists? Does it in fact matter? I have seen examples
of both


Thanks

-Mike
 
V

Victor Bazarov

Michael H Lees said:
As I see it there are two options for checking if for an element with
key 'x' exists in a map m....

1.) if(m.find(x)!=m.end())

or

2.) if(m.count(x))


They both take O(log N) where N is number of elements. Obviously they
both provide different things but which method should you use for just
checking if a key exists? Does it in fact matter? I have seen examples
of both

It doesn't matter. IMHO, if it's a map<>, where keys are single,
using 'count' is a bit counterintuitive (pun intended). Use whatever
you find more attractive (pun intended).

Victor
 
D

David Cattarin

Victor Bazarov said:
It doesn't matter. IMHO, if it's a map<>, where keys are single,
using 'count' is a bit counterintuitive (pun intended). Use whatever
you find more attractive (pun intended).

LOL. That's pretty cute.

However, I'd say use whatever you think other people would find
intuitive. If there is any possiblility that someone else will have to
maintain your code, take pitty on the poor slob and use find. Odds are
that using count would just confuse other people.

Dave
 
S

Samuele Armondi

Michael H Lees said:
Hi all,

As I see it there are two options for checking if for an element with
key 'x' exists in a map m....

1.) if(m.find(x)!=m.end())

or

2.) if(m.count(x))


They both take O(log N) where N is number of elements. Obviously they
both provide different things but which method should you use for just
checking if a key exists? Does it in fact matter? I have seen examples
of both


Thanks

-Mike
I would stick to find(), as it conveys the meaning of what you are trying to
do. It will save some poor maintenance coder scratching his head over coffee
for 2 hours!
S. Armondi
 

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,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top