我想检查类实例是否已经存储在std::vector中
I want to check if a class instance is already stored in a std::vector
我希望标题能完整地描述我的问题。
运行代码,我得到一个错误:
错误C2678: binary '==':没有找到带左操作数的操作符(或者没有可接受的转换)"
错误在哪里,我如何解决这个问题?
class A
{
private: //Dummy Values
int x;
int y;
}
class B
{
private:
vector <A> dataHandler;
public:
bool isElement(A element);
//Should return true if element exists in dataHandler
}
bool B::isElement(A element)
{
int length = dataHandler.size();
for(int i = 0; i<length; i++)
{
if(dataHandler[i] == element) //Check if element is in dataHandler
return true;
}
return false;
}
在isElement
中
if(dataHandler[i] == element)
这是试图使用operator==
比较两个A
实例,但是你的A
类没有实现任何这样的操作符过载。您可能想要实现一个类似的
class A
{
private: //Dummy Values
int x;
int y;
public:
bool operator==(A const& other) const
{
return x == other.x && y == other.y;
}
};
同样,可以用std::find
代替for
循环重写isElement
bool B::isElement(A const& element) const
{
return std::find(dataHandler.begin(), dataHandler.end(), element) != dataHandler.end();
}
编译器告诉你一切。为class A
定义operator==
。将class A
更新为如下内容:
class A
{
private: //Dummy Values
int x;
int y;
public:
bool operator==(A const& rhs) const
{
return x == rhs.x && y == rhs.y;
}
};
您必须为A
类编写自己的==
操作符,例如
bool operator==(const A &rhs) const
{
return this->x == rhs.x && this->y == rhs.y;
}
否则无法知道如何比较A
对象
您必须实现operator==
.
operator==
(内联非成员函数)示例:
inline bool operator== (const A& left, const A& right){
return left.getX() == right.getX() && left.getY() == right.getY();
}
相关文章:
- std::原子加载和存储都需要吗
- 如何从存储在std::映射中的std::集中删除元素
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- 在std::vector上存储带有模板的类实例
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 将无符号字符的向量存储在数组中会给我 std::bad_alloc
- 如何调用存储在指向"std::函数"的指针中的 lambda?
- 如何访问存储在 std::variant 中的类的方法
- std::vector move 而不是交换到空 vector 并释放存储
- 将可变参数模板类存储到 std::vector 中
- 在 std::vector<无符号字符中存储任意数据的方法>
- 存储 std::list 元素的地址;内存
- 在 C++11 智能指针中存储 std::thread
- 存储 std::p romise<R&>:"通信对象"
- 如果类型需要模板,如何存储std ::向量
- 在“std::map”中插入一个“int”值,该值应该存储“std::string”
- 这是存储 std::分配器状态的正确方法 - 在这种情况下,由 Windows 上的共享内存支持
- 为什么 libstdc++ 以相反的顺序存储 std::tuple 元素
- 模板化存储std::vector中的多种不同类型
- 存储 std::shared_ptr 的向量,<Foo>其中 Foo 是一个模板化类