0

I have a source code which contains as follows:

#include <iostream> 
#include <algorithm> 
#include <vector>
using namespace std; 

struct st
{
    int id;
    double d;
}; 

bool comp(int a, int b) 
{ 
    return (a < b); 
} 

bool comp2(st &a, st& b) { return a.d < b.d; }

int main() 
{
    vector<int> v = { 9, 4, 7, 2, 5, 15, 11, 12, 1, 3, 6 };
    vector<st> vec = {{1, 5.6},{2, 5.7},{3, 4.3}};

    auto max = std::max_element(v.begin(), v.end(), comp);
    cout << "Max element of v: " << *max; // It's working

    auto max2 = std::max_element(vec.begin(), vec.end(), comp2);
    cout << "Max element of vec: " << *max2; // It's not working

    return 0; 
}

When I try display the maximum value of vector vec I get the following error:

[Error] cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'

What is the possible solution to the problem?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Gabriel90
  • 101
  • 7
  • 3
    1) That's not a complete error message. 2) Your `st` doesn't have `operator<< (std::ostream&, st const&)` defined, hence it cannot be printed with `operator <<` (related, possibly: [How to properly overload the << operator for an ostream?](https://stackoverflow.com/questions/476272/how-to-properly-overload-the-operator-for-an-ostream). – Algirdas Preidžius Jun 02 '20 at 11:47
  • tip: try to focus on one thing at a time. Your current problem is not the vector and not getting the maximum. You'd get similar error for `st x; std::cout << x;`. The less code you have, the easier is it to fix – 463035818_is_not_an_ai Jun 02 '20 at 11:54

1 Answers1

2

You did not define the operator << for objects of the type struct st. So the compiler issues an error for this statement

cout << "Max element of vec: " << *max2;

Instead you could write for example

cout << "Max element of vec: " << max2->id << ", " << max2->d << '\n';

Or you cold define the operator << for objects of the type struct st something like

std::ostream & operator <<( std::ostream &os, const st &obj )
{
    return os << "( " << obj.id << ", " << obj.d << " )";
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335