在 [] 运算符的情况下,为 unordered_map 中的元素设置默认构造函数
Set a default constructor for an element in an unordered_map in case of [] operator
我有这个class:
class test_t {
public:
int value;
test_t() { }
test_t(int _value) : value(_value) { }
};
现在我创建了一个 unordered_map 以 int 值作为键
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) { }
然而 class 测试只是更复杂的例子。
[] operator
值初始化映射值,如果它没有找到它并且你不能改变它。不过,您可以更改默认初始化程序。
test_t() { value = 5;}
如果您想在键不在映射中的情况下插入您选择的值,一种方法是使用 find
获取键值对的迭代器,如果迭代器是end
迭代器,然后插入你的键值对。
根据@PaulMcKenzie 的建议,您可以选择使用 insert,因为 "it returns a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a bool denoting whether the insertion took place."
m.insert({key, test_t(5)});
我有这个class:
class test_t {
public:
int value;
test_t() { }
test_t(int _value) : value(_value) { }
};
现在我创建了一个 unordered_map 以 int 值作为键
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) { }
然而 class 测试只是更复杂的例子。
[] operator
值初始化映射值,如果它没有找到它并且你不能改变它。不过,您可以更改默认初始化程序。
test_t() { value = 5;}
如果您想在键不在映射中的情况下插入您选择的值,一种方法是使用 find
获取键值对的迭代器,如果迭代器是end
迭代器,然后插入你的键值对。
根据@PaulMcKenzie 的建议,您可以选择使用 insert,因为 "it returns a pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and a bool denoting whether the insertion took place."
m.insert({key, test_t(5)});