我正在尝试从std :: map获取具有最大值的元素,
int main() {
map<int, int> m;
m[1] = 100;
m[2] = -1;
auto x = std::max_element(m.begin(), m.end(), m.value_comp());
cout << x->first << " : " << x->second << endl;
}
Run Code Online (Sandbox Code Playgroud)
为什么它打印第二个元素2 : -1?
Lev*_*evi 18
取自这里:
auto x = std::max_element(m.begin(), m.end(),
[](const pair<int, int>& p1, const pair<int, int>& p2) {
return p1.second < p2.second; });
Run Code Online (Sandbox Code Playgroud)
这不是使用std::map::value_comp()(比较键值)而是查看second对中包含值的成员.这使用lambda表达式,因此您必须使用C++ 11支持进行编译
http://www.cplusplus.com/reference/map/map/value_comp/
Returns a comparison object that can be used to compare two elements to get whether
the key of the first one goes before the second.
Run Code Online (Sandbox Code Playgroud)
并且 2 > 1.value_comp比较键值,而不是值值。因为这就是 C++ 的运行方式。
| 归档时间: |
|
| 查看次数: |
28434 次 |
| 最近记录: |