By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,305 Members | 1,834 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,305 IT Pros & Developers. It's quick & easy.

Find unused ID.

P: n/a
I've map<unsigned int, Class*>. I'd like to find unused ID.
Is it easier (and/or faster) code:
template<class Class>
int findID(map<unsiged int, Class*>)
{
unsigned int max;
set<unsigned int> Set;
for(map<unsigned int, Class*>::iterator it = mymap.begin(); it !=
mymap.end; it++)
{
Set.insert(it->first);
if(it->first > max)
max = it->first;
}
for(unsigned int i = 0; i <= max; i++)
if(Set.find(i) == Set.end())
return i;
return max + 1;
}
Regards.
--
Linux user: #376500 (patrz http://counter.li.org/)
Jul 23 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Uzytkownik a écrit :
I've map<unsigned int, Class*>. I'd like to find unused ID.
Is it easier (and/or faster) code:
template<class Class>
int findID(map<unsiged int, Class*>)
{
unsigned int max;
set<unsigned int> Set;
for(map<unsigned int, Class*>::iterator it = mymap.begin(); it !=
mymap.end; it++)
{
Set.insert(it->first);
if(it->first > max)
max = it->first;
}
for(unsigned int i = 0; i <= max; i++)
if(Set.find(i) == Set.end())
return i;
return max + 1;
}
Regards.


Just look for it directly in the map:
for ( unsigned int i=0;
i < std::numeric_limits<unsigned int>::max();
i++)
if (mymap.find(i) != mymap.end())
return i;

It may not be the fastest code, but it is the easiest.

The fastest should be:
unsigned int i = 0;
for ( map<unsigned int, Class*>::iterator it = mymap.begin();
it != mymap.end();
it++, i++))
if (it->first != i)
return i;

Indeed, inside std::map, the data is sorted by its key member, so you
just have to check non corresponding ones.

--
Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.