关联容器将元素与键相关联。插入或从容器中查找元素需要等效键。通常,容器要求键是特定类型的,这会导致调用站点的效率低下,需要在接近等效的类型(如 std::string 和 absl::string_view)之间进行转换。
为了避免这种不必要的工作,一些容器提供了异构查找。此功能允许调用者传递任何类型的键(只要用户指定的比较器函子支持它们)。有关 stl 容器中此功能的示例,请参见 std::find。
使用异构查找来提高性能
使用异构查找的一个常见原因是性能。我们可以构造 key_type,但这样做需要我们宁愿避免的非平凡工作。例如:
std::map m = ...;absl::string_view some_key = ...;// construct a temporary `std::string` to do the query.// the allocation + copy + deallocation might dominate the find() call.auto it = m.find(std::string(some_key)); instead, we can use a transparent comparator like so:
struct stringcmp { using is_transparent = void; bool operator()(absl::string_view a, absl::string_view b) const { return a < b; }};std::map m = ...;absl::string_view some_key = ...;// the comparator `stringcmp` will accept any type that is implicitly// convertible to `absl::string_view` and says so by declaring the// `is_transparent` tag.// we can pass `some_key` to `find()` without converting it first to// `std::string`. in this case, that avoids the unnecessary memory allocation// required to construct the `std::string` instance.auto it = m.find(some_key); stl 容器支持和替代方案
有序容器 (std::{map,set,multimap,multiset}) 从 c++14 开始支持异构查找。从 c++17 开始,无序容器仍然不支持它。有添加此功能的建议,但尚未被接受。
gtl 容器支持
在 gtl/absl 中支持异构查找的容器包括:
go/btree:btree 容器 absl::btree_{set,map,multiset,multimap}。它们隐含地支持对具有常见比较器的类字符串键的异构查找,例如 std::less 其中 t 是 {std::string, absl::string_view, absl::cord} 之一(对于 std::greater )。所有其他密钥类型都需要用户明确选择加入。
go/swisstable:无序容器 absl::{flat,node}_hash_{set,map}。它们要求哈希函数和相等函数都被标记为透明的。出于性能原因,swisstable 隐式支持字符串键表的异构查找。所有其他密钥类型都需要用户明确选择加入。
扁平有序容器 gtl::flat_{set,map,multiset,multimap}。
gtl::lockfreehash{set,map}。
本文那个题目的答案是 none of the above: this code is correct and efficient.
台厂逆势突围、已逐渐看到拓展利基型产品的成果
液位开关维护和保养有哪些注意事项
7000应用开发技巧:模拟设备驱动(Mocking)
影响富镍正极低压区容量的因素
汽车冷凝器怎么清洗_汽车冷凝器的种类
C++: 使用异构查找来提高性能
沃达丰将采用华为5G设备在西班牙的15个城市投入运营
GP232RNL——USB到UART桥接控制器
友恩半导体U651X3系列的三款开关电源芯片介绍
山东省科学院激光研究所刘统玉:光纤传感赋能煤矿安全
机器人产业纳入2030的国家重大项目 产业风口来袭
佳能推出FPA-1200NZ2C纳米压印半导体制造设备
生物医疗市场前景将大有可为
新型VDM28激光测距传感器的应用优势介绍
字节流和字符流有什么区别?看完就知道!
新能源汽车行业加速前行 充电设施是制约新能源汽车普及发展的重要因素
发动机冷却系统分类及工作原理
加拿大大四学霸,天才程序员和他的逆天语言模型
美国海军两大旗舰蓝岭号、惠特尼山号已经不再适合担任旗舰
中兴FTTR常用业务配置指导(上)