Does std :: map support cache support?

For instance:

code1:

if((iter = map.find(key)) != map.end()) { return iter->second; } return 0; 

code2:

 if(map.count(key) > 0) { return map.at(key); } return 0; 

code2 is much simpler, but both map.count() and map.at() cost O (logn) time. Does std::map provide a function that stores the last search item in the cache and speeds up the search for the same item, or only performs a second search on the entire map?

+4
source share
3 answers

It searches the entire map, caching is not performed - or at least the standard does not provide any credentials, and I would say that it does not do any implementation, because all clients of such an implementation will have to pay for possibly unwanted service data for updating cached information after each insert / delete.

The first approach is an idiomatic way to determine if a key / value pair is in the map (just use the fact that operator -> should be used instead of operator . , Because what you get from find() is an iterator, and the assignment iter should be out of condition if ):

 auto iter = map.find(key); if (iter != map.end()) { return iter->second; } 
+5
source

No, none of the C ++ standard library implementations use caching as far as I know. C ++ 11 requires containers to be thread safe for multiple readers. And for this you need to synchronize access to the cache. This will result in a speed penalty, even if you do not want to. The standard C ++ practice is that you do not have to pay for everything that you clearly do not need or want.

+4
source

He could, but I don’t know, what I know. An idiomatic solution in this way is to use a variable:

 auto results = myMap.find( key ); return results == myMap.end() ? NULL : &results->second; 

Short, clean and easy to understand. (And this avoids multiple returns that make it difficult to justify the correctness of the program.)

+1
source

Source: https://habr.com/ru/post/1479120/


All Articles