2017-10-15 107 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相關的對有關? –