class Tuple
{
private:
vector<string> values;
public:
Tuple(vector<Parameter> newValues)
{
for(int i = 0; i < newValues.size(); i++)
{
string val = newValues[i].getValue();
values.push_back(val);
}
}
Tuple(vector<string> newAttributes)
{
values = newAttributes;
}
~Tuple()
{
}
bool operator < (Tuple &tup)
{
if(values < tup.getStringVec())
return true;
return false;
}
bool operator <= (Tuple &tup)
{
if(values <= tup.getStringVec())
return true;
return false;
}
bool operator > (Tuple &tup)
{
if(values > tup.getStringVec())
return true;
return false;
}
bool operator >= (Tuple &tup)
{
if(values >= tup.getStringVec())
return true;
return false;
}
};
class Relation
{
private:
set<Tuple> tupleSet;
public:
Relation():
{
}
~Relation()
{
}
void addToTupleSet(Tuple newTuple)
{
tupleSet.insert(newTuple); //<<this causes the problem
}
};
最佳答案
std::set
的默认比较器使用 std::less<T>
,这需要将对象暴露给 operator <
某种形式。这通常是以下两种形式之一:
一个免费的函数,像这样:
bool operator <(const Tuple& arg1, const Tuple& arg2);
或者一个成员函数,像这样:
class Tuple
{
public:
bool operator <(const Tuple& arg) const
{
// comparison code goes here
}
};
如果你不想执行operator <
仅用于 std::set
您当然可以直接实现自己的二进制比较器类型,并将其用作 std::less<T>
的比较器替代方案.您是否这样做是您的决定,以及针对不同问题的不同解决方案(即如何做到这一点,Niyaz 在另一个答案中对此进行了介绍)。
您的代码,稍作修改以不吸收命名空间 std
并在适当的地方使用引用(顺便说一句,您可能想看看那些,因为它们会显着减少您来回复制数据所花费的时间)。
#include <iostream>
#include <string>
#include <iterator>
#include <vector>
#include <set>
// I added this, as your source included no such definition
class Parameter
{
public:
Parameter(const std::string s) : s(s) {}
const std::string& getValue() const { return s; }
private:
std::string s;
};
class Tuple
{
private:
std::vector<std::string> values;
public:
Tuple(const std::vector<Parameter>& newValues)
{
for(auto val : newValues)
values.push_back(val.getValue());
}
Tuple(const std::vector<std::string>& newAttributes)
: values(newAttributes)
{
}
// note const member and parameter. neither the passed object nor
// this object should be modified during a comparison operation.
bool operator < (const Tuple &tup) const
{
return values < tup.values;
}
};
class Relation
{
private:
std::set<Tuple> tupleSet;
public:
void addToTupleSet(const Tuple& tup)
{
tupleSet.insert(tup);
}
};
int main(int argc, char *argv[])
{
Tuple tup({"a","b","c"});
Relation rel;
rel.addToTupleSet(tup);
return 0;
}
关于c++ - set<> 类,当我插入类时,它不接受我的 < 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19886422/