简体   繁体   中英

Can't compile on std::min_element's return

#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;
}

I wish to compute the minimum in the map.

This code failed to compile. I thought the way to use std::min_element 's returned iterator is by referencing it. No?

The error message on the std::cout line is "invalid operands to binary expression".

std::map::iterator::value_type (ie. the type of *it ) is std::pair<const double,double> , and there is no standard overload of operator<<(std::ostream &, std::pair<const double,double>) .

You could either define one, or do something like std::cout << it->first << ' ' << it->second << std::endl; .

The element type of std::map is a std::pair<const key_type, mapped_type> . *it will give you a reference to that. There is no output output operator defined for std::pair so the code fails to compile.

You will either have to add an overload for it like

std::ostream& operator <<(std::ostream& os, const std::pair<const double, double>& e)
{
    return os << "{" << e.first << ", " << e.second << "}\n";
}

or just print what you want like

std::cout << it->first << " " << it->second << "\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM