Severity Code Description Project File Line Suppression State
Error C2678 binary '<': no operator found which takes a left-hand operand of type 'const studentinfo' (or there is no acceptable conversion) studentrecord c:\program files (x86)\microsoft visual studio\2017\enterprise\vc\tools\msvc\14.10.25017\include\xstddef 234
i am not sure why. i am not even using the "<" operator.
You are using std::sort() correctly, and even made a sort function (which you named 'name' ???).
The problem is that a std::set() wants to sort its elements, but has no idea how to sort studentinfos. This is where the < operator comes in: you want to provide a version that knows how to work on studentinfo arguments.
Your 'name' function is exactly that, just with the unfortunate name. Rewrite it thus:
template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
... comp - comparison function object
A function object can be for example a functor (a class a member of which overloads operator() ), a lambda (which is converted into a functor by the compiler), all these strange ‘beasts’ here: http://en.cppreference.com/w/cpp/utility/functional
So, following the examples provided by cppreference.com, you can:
1) wrap your ‘normal’ function into a function object by means of std::function:
We can use a 'normal' function, as long as it meets the requirements specified by the Compare concept
Definitely, JLBorges! Thanks a lot for your correction. I’ve been set on the wrong track by the error the OP reported (“Error C2678 binary '<': no operator found which takes a left-hand operand of type 'const studentinfo'”), which was likely due by the (wrong) sort() on std::set, not the one on std::vector, which was fine.
I gave a hasty answer: my bad.
ostream& operator <<(ostream& os, studentinfo & c)
{
os << c.name << " " << c.grade ;
return os;
}
//
//template<typename T>
//void print(T& c)
//{
// cout << "\nHere is the List: \n";
// for (auto& x : c) //& pass by ref is required if process modifies the element
// cout << x << " ";
// cout << "\n" << endl;
//}
why is it necessary to have this line inside the struct:
bool operator<(const studentinfo& other) const { return name < other.name; }
i thought that the predicate function on line 47 takes care of everything:
bool cmp_names(const studentinfo& lhs, const studentinfo& rhs) { return lhs.name < rhs.name; }
Your post would be so much easier to read if you had used the “code” tags...
cmp_names() can take care of everything if you pass it to the std::set constructor, as JLBorges showed you: