将 unordered_map 分配给一对对象 [英] Assigning of unordered_map to pair of objects
问题描述
我正在尝试理解 unordered_map
赋值,我收到以下错误:没有匹配的函数用于调用 std::pair<foo, foo>::pair()代码>,根据
unordered_map operator[]
的文档:
I am trying to understand the unordered_map
assignment, I get the following error: no matching function for call to std::pair<foo, foo>::pair()
, according to the doc for unordered_map operator[]
:
如果 k 与容器中任何元素的键都不匹配,该函数将插入一个具有该键的新元素并返回对其映射值的引用.
If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value.
所以我试图将一个对象(来自 make_pair
)分配给这个引用,我猜这是不允许的.但是,对于 pair
,它可以工作,然后我想知道是否必须为 foo
声明一些其他运算符才能使其工作.
So I am trying to assign an object (from make_pair
) to this reference, which I am guessing is not allowed. However with the pair<int,int>
, it works, then I am wondering if I must declare some other operators for foo
to make this work.
#include <bits/stdc++.h>
using namespace std;
struct foo {
int n;
foo(int n): n(n) {};
};
int main(){
unordered_map<int, pair<foo,foo>> m;
//m[3] = make_pair(foo(1),foo(2)); <--- error here
unordered_map<int, pair<int,int>> ii;
ii[3] = make_pair(1,2);
}
推荐答案
问题在于 operator []
可能必须构造一个值对象,在您的情况下为 std::pair<foo, foo>
.由于 foo
没有默认构造函数,所以它不能构造默认的 std::pair
.
The problem is that operator []
might have to construct a value object, in your case std::pair<foo, foo>
. Since foo
doesn't have a default constructor, it can't construct the default std::pair
.
您可以为 foo
提供默认构造函数(包括为 n
添加默认值),或者您必须使用另一种方法将值插入 <代码>m.
You can either provide a default constructor for foo
(including adding a default value for n
), or you'll have to use another method to insert values into m
.
这篇关于将 unordered_map 分配给一对对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!