为什么在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, Value>, 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()(为second

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

template <
class Key,
class Value, // <<===============
class Compare = std::less<Key>,
class Allocator = std::allocator<std::pair<Key, Value>>,
class GrowthPolicy = void,
class Container = std::vector<std::pair<Key, Value>, Allocator>>   // <<===============
class sorted_vector_map : detail::growth_policy_wrapper<GrowthPolicy> {
detail::growth_policy_wrapper<GrowthPolicy>& get_growth_policy() {
return *this;
}
template <typename K, typename V, typename C = Compare>
using if_is_transparent =
_t<detail::sorted_vector_enable_if_is_transparent<void, C, K, V>>;
struct EBO;
public:
typedef Key key_type;
typedef Value mapped_type; // <<===============
typedef typename Container::value_type value_type; // <<===============
typedef Compare key_compare;
typedef Allocator allocator_type;
typedef Container container_type;

相关内容

最新更新