我正在嘗試返回std::map
的最大值。爲什麼C++編譯器在參數中不使用const時編譯失敗?
int main() {
int N;
cin >> N;
map<int,int > m;
while(N--) {
int x; cin >> x;
m[x]++;
}
cout << max_element(m.begin(), m.end(), pred)->first;
return 0;
}
如果我定義pred
這樣的,它的工作原理:
bool pred(const pair<int,int>& lhs, const pair<int,int>& rhs){
return lhs.second < rhs.second;
}
然而,這不起作用:
bool pred(pair<int,int>& lhs, pair<int,int>& rhs){
return lhs.second < rhs.second;
}
我不明白爲什麼const
允許它的工作。
將參數更改爲pair&',然後重試。顯然,map鍵是一個'const'。顯然,您不能在地圖上更改某個特定值的密鑰。 –
是的,但我不想改變任何東西。爲什麼我需要const? – sbryan1
您需要const,因爲您無法在程序的任何部分合法地轉換或轉換const。這就是所謂的const正確性,在C++中它是類型安全的一部分。如果您嘗試將const事傳遞給一個採用非const引用的函數,那麼這是一個編譯錯誤。 const的東西不能綁定到非const引用。 –