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

2
  • In your case if you constructed the map with the keys as your values and values as your keys, the minimum value would just be *A.begin() since std::map stores its elements in sorted order. Commented Sep 19, 2018 at 13:26
  • Using double as key for std::map is usually not a good idea Commented Sep 19, 2018 at 13:53

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.