首页 > 解决方案 > Set a default constructor for an element in an unordered_map in case of [] operator

问题描述

I have this class:

class test_t {

public:

  int value;

  test_t() { }

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

};

Now I have create a unordered_map with the a int value as key

std::unordered_map<int, test_t> map;

When I will use the operator [] if the key it not exist a new element will be add to the map calling the construct.

test_t & test = map[0];

Now it si possible to tell to the unordered_map to call the other constructor? i.e. is is possibile to do something like this?

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

in the means that every new element will be create whit the construction with value 5?

I know that i can create a construction like this:

test_t(int _value = 5) { }

however the class test is only a example of something more complex.

标签: c++c++11unordered-map

解决方案


[] operatorvalue 如果找不到映射值并且您无法更改它,则初始化它。不过,您可以更改默认初始化程序。

test_t() { value = 5;}

如果您想插入您选择的值以防键不在映射中,一种方法是使用find获取键值对的迭代器,如果迭代器是end迭代器,则插入您的键值对。

可选地,正如@PaulMcKenzie 所建议的那样,您可以只使用insert,因为“它返回一个由插入元素(或阻止插入的元素)的迭代器和一个表示插入是否发生的布尔值组成的对。”

m.insert({key, test_t(5)});

推荐阅读