关于C ++ std :: pair的奇怪的编译错误

时间:2017-10-15 23:35:59

标签: c++ stl

这是代码和错误消息,有什么想法的原因?我删除了这行代码Building t = beginEndMap[b.id];后尝试编译即可。但无法弄清楚这条线的偶然错误。该行与对不相关,但编译错误与对有关。

错误消息

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() {

}

1 个答案:

答案 0 :(得分:2)

原因

长话短说,如果您使用unordered_map::operator[],则Building需要DefaultConstructible,而不是operator[]。因此(criptic)错误。

这是因为如果找不到密钥,value_type会进行插入。

要求如下:

  

std::pair<const int, Building>(a.k.a EmplaceConstructible(我的注))必须是std::piecewise_construct, std::forward_as_tuple(key), std::tuple<>() 来自

key_type
     

使用默认分配器时,这意味着intCopyConstructible   在你的情况下)必须是mapped_type Building   (在您的情况下为DefaultConstructible)必须为Building

解决方案

unordered_map::at的默认构造函数,或者使用std::pair,如果找不到密钥则会抛出,因此它没有此要求。

  

为什么编译错误与对有关的东西有关   到unsorted_map?

因为内部使用key来存储value - {{1}}对。

  

无序映射是一个包含键值的关联容器   配对与唯一键

因为当你有模板时会得到这些类型的criptic错误。 C ++概念正在进行中,它将(希望)大大改善这种错误。

std::unordered_map::operator[]