SmallChess
SmallChess

Reputation: 8116

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".

Upvotes: 2

Views: 98

Answers (2)

NathanOliver
NathanOliver

Reputation: 180500

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";

Upvotes: 4

SirGuy
SirGuy

Reputation: 10770

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;.

Upvotes: 7

Related Questions