所以我创建了一个名为 Tuples 的新类,其中 Tuples 接受一个称为 tupleVector 的字符串 vector 。然后我创建了一组元组,这意味着我需要重载对元素进行排序和禁止重复所需的运算符。
两个问题:
- 哪个运算符重载是必要的?我是否重载了 < 或 ==?
假设我必须在我的 Tuples 类中执行此重载(以便我可以在其他类中使用 Tuples 集),以下代码是否正确?
include "Tuples.h" Tuples::Tuples(vector<string> tuple){ tupleVector = tuple; } vector<string> Tuples::getStrings() { return tupleVector; } bool Tuples::operator<(Tuples& other){ return this->tupleVector<other.tupleVector; } bool Tuples::operator==(const Tuples& other)const{ return this->tupleVector==other.tupleVector; } Tuples::~Tuples() { // TODO Auto-generated destructor stub }
最佳答案
您只需提供operator<
.容器通过反身比较来检查两个项目是否等价:如果!(a<b) && !(b<a)
,它们就等价。
关于c++ - C++中集合的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22392208/