为[]运算符,为unordered_map中的元素设置默认构造函数

问题描述 投票:0回答:1

我有这个课:

class test_t {

public:

  int value;

  test_t() { }

  test_t(int _value) : value(_value) { }

};

现在我已经创建了一个以int值作为键的unordered_map

std::unordered_map<int, test_t> map;

当键不存在时,我将使用运算符[]时,会将新元素添加到调用该构造的映射中。

test_t & test = map[0];

现在可以告诉unordered_map调用其他构造函数了吗?即可以做这样的事情吗?

std::unordered_map<int, test_t(5)> map;

意味着每个新元素都将用值5的构造创建?

我知道我可以创建这样的构造:

test_t(int _value = 5) { }

但是类测试只是更复杂的例子。

c++ unordered-map
1个回答
0
投票

[] operator值,如果找不到它且您无法更改它,则初始化它。您可以更改默认的初始化程序。

© www.soinside.com 2019 - 2024. All rights reserved.