c++ - 比较类和对象的向量时如何定义 == 运算符?
问题描述
我希望我的程序在向量具有相同颜色超过 3 次时停止。在这里,我使用了 'if(b==all_colors[i])' 但我得到了错误。这是因为我没有使用模板吗?我必须重写整个代码吗?
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
class Bag
{
string marble;
public:
Bag(string marble)
{
this->marble=marble;
}
string add_marble()
{
return marble;
}
};
class Marble_exception
{
vector<Bag>all_colors;
int count=0;
public:
void add_color(Bag b)
{
for(int i=0; i<all_colors.size(); i++)
{
if(b==all_colors[i])
{
count++;
}
}
if(count>=3)
{
cout<<"Sorry, you already have three of these marbles.\n\n";
}
else
{
all_colors.push_back(b);
cout<<"added.\n\n";
}
}
};
解决方案
不,您不必重写整个代码。错误是因为operator==
您的Bag
班级没有。C++ 知道如何比较vector<T>
,但前提是它也知道如何比较T
。将此添加到您的代码中
class Bag
{
...
// new code
friend bool operator==(const Bad& x, const Bag& y)
{
return x.marble == y.marble;
};
// new code
};
这段代码定义了operator==
for所以现在使用forBag
应该没有问题。==
vector<Bag>
推荐阅读
- python - 具有定义函数的等高线图,其中输入为向量
- macos - 如何在 swift 和 Hal 驱动程序编写的应用程序之间共享数据
- shell - ZSH:读取时从内部输出的标准输出丢失
- c# - c# adobe acrobat SDK:SDK退出后文件仍被锁定
- r - 在R中没有标题的数据框前面插入一列
- python - 我如何将 Django - Tenant 与 Django Haystack 集成
- elasticsearch - 如何使用自定义序列化程序序列化类型信息也用于使用 NEST 和 Elasticsearch 的子文档
- javascript - 在反应页面之间加载微调器
- html - 带有表格的简单 HTML 联系方式表单
- ios - 有没有办法从 Healthkit 获得多个数据点的集体许可