从 std::map 中查找具有最大值的元素
find element with max value from std::map
我正在尝试从 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;
}
为什么它打印第二个元素 2 : -1
?
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.
and 2 > 1. value_comp
比较 key 值,而不是 value 值。因为这就是 C++ 的运行方式。
摘自here:
auto x = std::max_element(m.begin(), m.end(),
[](const pair<int, int>& p1, const pair<int, int>& p2) {
return p1.second < p2.second; });
这不是使用 std::map::value_comp()
(比较键值)而是查看对中包含值的 second
成员。这使用了 lambda 表达式,因此您必须使用 C++11 支持进行编译
我正在尝试从 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;
}
为什么它打印第二个元素 2 : -1
?
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.
and 2 > 1. value_comp
比较 key 值,而不是 value 值。因为这就是 C++ 的运行方式。
摘自here:
auto x = std::max_element(m.begin(), m.end(),
[](const pair<int, int>& p1, const pair<int, int>& p2) {
return p1.second < p2.second; });
这不是使用 std::map::value_comp()
(比较键值)而是查看对中包含值的 second
成员。这使用了 lambda 表达式,因此您必须使用 C++11 支持进行编译