当前位置:网站首页>Tips of the week 136: unordered containers

Tips of the week 136: unordered containers

2022-07-07 17:58:00 -Flying crane-

TotW#136 Originally published in 2017 year 6 month 23 Japan
from Matt Kulukundis A literary creation
“ Sometimes , When the material is really good , You will place expectations on yourself , To make it the best program . You don't just provide hashes for rules , Go on with your work , Then go home .”- Peter . Dinlaki
Cut a long story short , About the latest official recommendations , Please have a look at https://abseil.io/docs/cpp/guides/container. This tip introduces new types , But it is not a normative reference .

Introduce absl:_hash_map

There is a new series of related containers in towns . They boast of improving efficiency and providing services earlier than C++17 The interview of . They also provide developers with direct control over their implementation and default hash functions , This is important for the long-term development of the code base . New code should prioritize these types over std::unordered_map. All in the system map and set With std::unordered_map same API, So it's easy to switch to them .
For each absl::_hash_map for , There is also a absl::_hash_set; however , These charts will only describe map The situation of , And what we often mention is map.
absl::flat_hash_map and absl::flat_hash_set
 Insert picture description here

These should be your default choices . They store their value_type To the main array . Because when they scatter again, they move data , Element cannot make pointer stable . If you need pointer stability or your value is large , Please consider using absl::node_hash_map Instead of , perhaps Absl::flat_has-mak<Key,std::unique_ptr>.
absl::node_hash_map and absl::node_hash_set
 Insert picture description here

Attention : Because it's hashing like map[“a”]=map[“b”] Then invalid memory will be accessed , Unstable pointer .

They are allocated outside the main array value_type( Such as std::unordered_map). Because of these independent distributions , They provide pointer stability for stored data ( Stored in map The address of the object in does not change ), And the empty slot only needs 8 Bytes . in addition , They can store things that can neither be moved nor copied .

We usually recommend that you use absl::flat_hash_map<K, std::unique_ptr> instead of absl::node_hash_map<K, V>, about node_hash_set So it is with .

原网站

版权声明
本文为[-Flying crane-]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071522592115.html