C++ Can';t在std::min_元素上编译';回归 #包括 #包括 #包括 使用名称空间std; int main() { 地图A; const auto it=std::min_元素(A.begin(),A.end(), [](decltype(A)::value\u type&l,decltype(A)::value\u type&r)->bool{return l.second

C++ Can';t在std::min_元素上编译';回归 #包括 #包括 #包括 使用名称空间std; int main() { 地图A; const auto it=std::min_元素(A.begin(),A.end(), [](decltype(A)::value\u type&l,decltype(A)::value\u type&r)->bool{return l.second,c++,c++11,C++,C++11,std::map::iterator::value\u type(即*it的类型)是std::pair,并且没有operator的标准重载,std::map的元素类型是std::pair*它将为您提供一个参考。没有为std::pair定义输出运算符,因此代码无法编译 您必须为它添加一个重载,如 #include <map> #include <iostream> #include <algorithm> using namespace std; int m

std::map::iterator::value\u type
(即
*it
的类型)是
std::pair
,并且没有
operator的标准重载,
std::map
的元素类型是
std::pair
*它将为您提供一个参考。没有为
std::pair
定义输出运算符,因此代码无法编译

您必须为它添加一个重载,如

#include <map>
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    std::map<double, double> A;

    const auto it = std::min_element(A.begin(), A.end(),
                                [](decltype(A)::value_type& l, decltype(A)::value_type& r) -> bool { return l.second < r.second; });

    std::cout << *it << std::endl;
}

std::ostream&operator在您的例子中,如果使用键作为值和值作为键来构造映射,那么最小值就是
*A.begin()
,因为
std::map
按排序顺序存储其元素。使用
double
作为
std::map
的键通常不是一个好主意
std::ostream& operator <<(std::ostream& os, const std::pair<const double, double>& e)
{
    return os << "{" << e.first << ", " << e.second << "}\n";
}
std::cout << it->first << " " << it->second << "\n";