'std::set error: no match for »operator<« [duplicate]
I have a class (extract):
class Package
{
private:
string s_package_name;
float f_boottime;
float f_bytesize;
list <Package> l_depends;
list <Package> l_selects;
}
I'd like to generate many objects and list them in a unique "array", therefore i took set I add the objects like this:
set<Package> l_tempSet;
Package PackageA(1, 11, "what a package");
Package PackageB(2, 22, "what a 2nd package");
l_tempSet.insert(PackageA);
l_tempSet.insert(PackageB);
When compiling I receive an error Message:
no match for »operator<« (operand types are »const Package« and »const Package«)
When clicking into the Error Message it points me to the set.h to the line where unique is called and I think this is the error.
Is it true that C++ isn't capable to "unique" objects (like in this example) into lists and sets and can just handle easy data types like int, float etc. ? Or did I went wrong somewhere, please help me I'm not sure where the error is exactly.
Thanks for your suppport
Solution 1:[1]
The problem is, that a c++ std::set is orderd, therefore it needs to sort the elements by evaluating the operator<.
Basically there are three solutions to your problem:
Implement the
operator<for your class (see more here)bool operator<(const Package& other) const { //return true if this < other }Use an unsorted set like
std::unordered_set, but then you'll have to implement the equality operator and a hash function.Implement a comparator function and pass it to the
setas second template parameter:bool smaller (const Package& left, const Package& right) { //return true if left < right; } std::set<Package,std::function<bool(const Package&, const Package&)>> newSet (std::function<bool(const Package&, const Package&)>(smaller));
Solution 2:[2]
You have to define operator< for your class. Otherwise, set cannot compare objects it's supposed to store, thus cannot check their uniqueness.
Solution 3:[3]
When you use std::set, internal implementation may use operator < to arrange objects into buckets, RBTree etc.(Because std::set is ordered) So it needs operator <. Compiler doesn't provide comparision operator by default, so you need to implement 1 by yourself.
class Package
{
private:
string s_package_name;
float f_boottime;
float f_bytesize;
list <Package> l_depends;
list <Package> l_selects;
public:
bool operator <(const Package &t) {
/* your logic */
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alfishe |
| Solution 2 | el.pescado - нет войне |
| Solution 3 | Mohit Jain |
