2017-10-15 86 views
0

这里是代码和错误消息,为什么?我试过删除这行代码Building t = beginEndMap[b.id];后,编译就OK了。但是无法弄清楚这条线路的错误。这一行不是对相关的,但编译错误是对关联的。有关C++ std :: pair的怪异编译错误

错误消息

Error: 
    required from 'std::pair<_T1, _T2>::pair(std::piecewise_construct_t, std::tuple<_Args1 ...>, std::tuple<_Args2 ...>) [with _Args1 = {const int&}; _Args2 = {}; _T1 = const int; _T2 = Building]' 

源代码

struct Building { 
    int id; 
    int pos; 
    int height; 
    bool isStart; 
    Building(int i, int p, int h, int s) { 
     id = i; 
     pos = p; 
     height = h; 
     isStart = s; 
    } 
}; 

class Solution { 
public: 
    vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { 
     vector<Building> sortedBuilding; 
     unordered_map<int, Building> beginEndMap; 
     vector<pair<int, int>> result; 
     for (Building b : sortedBuilding) { 
      Building t = beginEndMap[b.id]; 
     } 
     return result; 
    } 
}; 

int main() { 

} 

回答

2

原因

长话短说,如果你使用unordered_map::operator[]然后Building需求是DefaultConstructible它ISN “T。因此(诡计)错误。

发生这种情况是因为如果未找到密钥,operator[]将执行插入操作。

的要求是这样的:

value_type(又名std::pair<const int, Building>(我注))必须EmplaceConstructible

std::piecewise_construct, std::forward_as_tuple(key), std::tuple<>() 

当使用默认的分配,这意味着key_typeint 在你的情况)必须是CopyConstructiblemapped_typeBuilding在你的案件)必须是DefaultConstructible

解决方案

是有一个默认的构造函数为Building,或使用unordered_map::at如果该键没有找到将抛出,因此它并没有这个要求。


为什么配对,而不是unsorted_map相关 一些其他相关的编译错误?

std::pair由于在内部用于存储key - value对。

无序的地图是包含键值 对具有独特的键

因为这几样criptic错误的,当你有模板,你得到一个关联容器。 C++概念正在进行中,这将(希望)大大改善这种错误。


std::unordered_map::operator[]

+0

但我的'key_type'比'Building',请参阅定义''是其他int' unordered_map beginEndMap',和你的意思'value_type'以外'为key_type '? –

+1

@ LinMa我不好。 'value_type'。我纠正了它。 – bolov

+0

谢谢,您的回复对我有意义,但为什么编译错误与unsorted_map相关的对有关? –