问题描述
我不明白 sorted_vector_map 中的运算符 [] 做了什么。
- 具体来说,当键不存在时,数据结构中添加什么值?
- 什么是
value_type(key,mapped_type())
? - 默认情况下是对
std::pair
的构造函数调用吗? - 什么是
mapped_type()
? - 它也是构造函数调用吗?
mapped_type& operator[](const key_type& key) {
iterator it = lower_bound(key);
if (it == end() || key_comp()(key,it->first)) {
return insert(it,value_type(key,mapped_type()))->second;
}
return it->second;
}
https://github.com/facebook/folly/blob/master/folly/sorted_vector_types.h#L1097
解决方法
答案在头文件中。
考虑:
value_type(key,mapped_type())
在您链接的文件的第 743 行,您将看到以下声明:
typedef typename Container::value_type value_type;
但什么是Container
?在第 728 行,您会发现 Container 是一个模板参数,它可能是一个 std::pair
(除非用户提供了另一个)。
class Container = std::vector<std::pair<Key,Value>,Allocator>>
所以是的,该行是一个构造函数调用以初始化一个 std::pair
,因为这是这个特定数据结构用作其值的内容。
mapped_type()
也是一个构造函数调用,没有参数。它类似于:
int i = int();
Container
是模板参数,用于定义 sorted_vector_map
使用哪个容器来存储键值对,默认为 std::vector
(std::vector<std::pair<Key,Allocator>>
)
value_type
是 Container::value_type
(typedef typename Container::value_type value_type;
) 其中(对于默认模板参数)是 std::pair<Key,Value>
(参见 std::vector Member types)
mapped_type
是 Value
(typedef Value mapped_type;
) 所以存储在 sorted_vector_map
什么是 value_type(key,mapped_type())?
什么是mapped_type()?
也是构造函数调用吗?
所以 value_type(key,mapped_type())
创建了一个 std::pair
,其中 key
为 first
,默认构造的 Value
(mapped_type()
) 为 {{1} }.
默认情况下是对 std::pair 的构造函数调用吗?
是的
second