Lynn McGuire <
l...@winsim.com> wrote in news:mv9qpk$d4g$
2...@dont-email.me:
> Here is my code:
>
> // find the first unused integer key and use it
> if ( ! found)
> {
> m_FormsMainCacheIndex = 0;
> while ( g_FormsMainCache.find (m_FormsMainCacheIndex) !=
> g_FormsMainCache.end () )
> m_FormsMainCacheIndex++;
> // In STL maps, is it better to use map::insert than
> []? //
>
http://stackoverflow.com/questions/326062/in-stl-maps-is
> -it-better-to-use-mapinsert-than
> g_FormsMainCache.insert ( std::pair <int, FormsMain>
> (m_FormsMainCacheIndex, * FmWindow) );
> }
The complexity of your algorithm is O(N*log(N)). A better approach would
be just iterate over the map,this would be just O(N):
int index = 0;
std::map<int, FormsMain>::iterator iter = cache.begin();
while(true) {
if (iter==cache.end() || iter->first!=index) {
cache[index] = *FmWindow;
break;
} else {
++iter;
++index;
}
}
Another option would be to use insert with a hint instead of []
cache.insert(iter, std::make_pair(index, *FmWindow));
This would avoid a bit of meaningless work (we already have located the
place where the insert should happen), but OTOH it can be considered as a
premature optimization as it would not change the overall complexity.
hth
Paavo