为什么 sorted_vector_map 中的 [] 运算符?

问题描述

我不明白 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_typeContainer::value_type (typedef typename Container::value_type value_type;) 其中(对于默认模板参数)是 std::pair<Key,Value>(参见 std::vector Member types

mapped_typeValue (typedef Value mapped_type;) 所以存储在 sorted_vector_map

中的值的类型

什么是 value_type(key,mapped_type())?
什么是mapped_type()?
也是构造函数调用吗?

所以 value_type(key,mapped_type()) 创建了一个 std::pair,其中 keyfirst,默认构造的 Value (mapped_type()) 为 {{1} }.

默认情况下是对 std::pair 的构造函数调用吗?

是的

second