Here's the code:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <utility>
struct student
{
std::string full_name;
int group;
int number;
friend std::istream& operator>>(std::istream& in, student& obj)
{
in >> obj.full_name >> obj.group >> obj.number;
return in;
}
friend std::ostream& operator<<(std::ostream& out, const student& obj)
{
out << "Full name: " << obj.full_name << '\n';
out << "Group: " << obj.group << '\n';
out << "Number: " << obj.number << '\n';
return out;
}
bool operator<(const student& obj)
{
return this->number < obj.number;
}
};
int main()
{
std::ifstream fin("input.txt");
student a, b;
fin >> a >> b;
std::cout << std::max(a, b) << " studies at senior course.";
}
Here's the errors:
In file included from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\char_traits.h:39,
from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\ios:40,
from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\ostream:38,
from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\iostream:39,
from 2.cpp:1:
c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\stl_algobase.h: In instantiation of 'constexpr const _Tp& std::max(const _Tp&, const _Tp&) [with _Tp = student]':
2.cpp:37:28: required from here
c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\stl_algobase.h:227:15: error: no match for 'operator<' (operand types are 'const student' and 'const student')
227 | if (__a < __b)
| ~~~~^~~~~
What's the problem? I could've used (a < b ? b : a)
instead of std::max()
and it would compiled, but still I don't understand what's the problem with second option. Tried to compile on visual studio compiler and g++, result is still the same.
You are missing a const
qualifier on comparison function:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <utility>
struct student
{
std::string full_name;
int group;
int number;
friend std::istream& operator>>(std::istream& in, student& obj)
{
in >> obj.full_name >> obj.group >> obj.number;
return in;
}
friend std::ostream& operator<<(std::ostream& out, const student& obj)
{
out << "Full name: " << obj.full_name << '\n';
out << "Group: " << obj.group << '\n';
out << "Number: " << obj.number << '\n';
return out;
}
bool operator<(const student& obj) const { return this->number < obj.number; }
};
int main()
{
std::ifstream fin("input.txt");
student a, b;
fin >> a >> b;
std::cout << std::max(a, b) << " studies at senior course.";
}