集合的集合的重载操作符
Overload operator for set of sets
我只是建立了一个小程序来了解这将如何工作,因为我需要这个东西有点困难,但我不能使这个工作。
我认为我需要定义操作符重载,但我不知道如何,因为它们是set<set<a>>
的两个对象
如果你编译你会看到一个很大的错误,它注意到他不能比较myset == myset2
,我想它会说同样的操作符!=
和=
#include <set>
using namespace std;
class a{
private:
int a_;
public:
int get_a() const{ return a_; }
void set_a(int aux){ a_=aux;}
bool operator < (const a& t) const{
return this->get_a() < t.get_a();
}
};
class b{
private:
set<set<a> > b_;
public:
void set_(set<a> aux){ b_.insert(aux); }
//Overload operators?
};
int main(){
b myset;
b myset2;
set<a> subset1;
set<a> subset2;
a myint;
myint.set_a(1);
subset1.insert(myint);
myint.set_a(2);
subset1.insert(myint);
myint.set_a(3);
subset1.insert(myint);
myint.set_a(5);
subset2.insert(myint);
myint.set_a(6);
subset2.insert(myint);
myint.set_a(7);
subset2.insert(myint);
myset.set_(subset1);
myset.set_(subset2);
myset2.set_(subset1);
myset2.set_(subset2);
if(myset == myset2){
cout << "They are equal" << endl;
}
if(myset != myset2){
cout << "They are different" << endl;
}
b myset3;
myset3 = myset2; //Copy one into other
}
为了让你的代码工作,你需要指定以下操作符(注意:它们不是默认创建的)
class a{
private:
int a_;
public:
int get_a() const{ return a_; }
void set_a(int aux){ a_=aux;}
/* needed for set insertion */
bool operator < (const a& other) const {
return this->get_a() < other.get_a();
}
/* needed for set comparison */
bool operator == (const a& other) const {
return this->get_a() == other.get_a();
}
};
class b{
private:
set<set<a> > b_;
public:
void set_(set<a> aux){ b_.insert(aux); }
/* needed, because myset == myset2 is called later in the code */
bool operator == (const b& other) const {
return this->b_ == other.b_;
}
/* needed, because myset != myset2 is called later in the code */
bool operator != (const b& other) const {
return !(*this == other);
}
};
您还应该查看http://en.cppreference.com/w/cpp/container/set,看看std::set
在其元素上内部使用了哪些其他操作符。
编译器默认不生成操作符(operator=(const T&)
和operator=(T&&)
除外)。您应该显式地定义它们:
class b{
private:
set<set<a> > b_;
public:
void set_(set<a> aux){ b_.insert(aux); }
//Overload operators?
bool operator==(const b& other) const {
return b_ == other.b_;
}
bool operator!=(const b& other) const {
return b_ != other.b_;
}
};
然而,这并不能解决问题。虽然已经为std::set<T>
定义了比较操作符,但只有在有T
操作符的情况下,比较操作符才有效。因此,在本例中,您必须按照与b
类相同的方式为a
类定义operator==
和operator!=
。
相关文章:
- 处理多个异常集合的C++方法
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- 如何将ampl中的集合表示为c++中的向量
- 检查值是否在集合p1和p2中,但不在p3中
- 带过滤器的现代迭代c++集合
- 如何将结构插入到集合中并打印集合的成员
- 集合上的输出迭代器:assign和increment迭代器
- 如何将函数集合传递给客户端类,以便将它们当作客户端类本身的成员使用
- 实现一个在集合上迭代的模板函数
- 尝试使用集合函数时出现分段错误
- 互斥指针的集合
- c++找不到具有相同哈希的无序集合元素
- python集合的C++等价物是什么.计数器
- 如何在C++中递归地按相反顺序打印集合
- Python 集合.计数器,如何避免重复查找
- 如何写向量的无序向量集,即unordered_set<向量<向量<int>>集合?
- 从具有自定义排序的向量创建集合
- 显示字符串的集合和子集
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 集合的集合的重载操作符