我正在尝试返回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引用。 –