[英]vector::erase fails with invalid operands to binary expression (T and const T)
I have a Class called Request like this,我有一个名为 Request 的 Class 像这样,
class Request {};
I store objects of this type in a global vector called,我将这种类型的对象存储在一个名为的全局向量中,
std::vector<Request> requests;
I initialize the object using,我使用初始化 object,
auto &request = requests.emplace_back();
Now, I attempt to delete the object using the reference provided by emplace_back
like this,现在,我尝试使用 emplace_back 提供的参考删除
emplace_back
,如下所示,
requests.erase(std::remove(requests.begin(), requests.end(), request), requests.end());
It fails to compile and outputs following error,它无法编译并输出以下错误,
sysroot/include/c++/v1\algorithm:2103:24: error: invalid operands to binary
expression ('Request' and 'const Request')
if (!(*__i == __value_))
~~~~ ^ ~~~~~~~~
What should I do here to make it compile?我应该怎么做才能使它编译?
In在
requests.erase(std::remove(requests.begin(), requests.end(), request), requests.end());
The asker has been confused by answers to problems with std::erase
and classes with no compiler-generated assignment operator.提问者对
std::erase
和没有编译器生成的赋值运算符的类的问题的答案感到困惑。 The problem here is not with std::erase
and assignment operators, Request
is, as presented at any rate, simple enough that the compiler will automatically generate an assignment operator for them.这里的问题不在于
std::erase
和赋值运算符,无论如何, Request
足够简单,编译器会自动为它们生成一个赋值运算符。 But keep an eye out for the Rule of Three and friends .但请留意三法则和朋友。 Just because a default assignment operator can be generated doesn't mean the default behaviour is logically correct.
仅仅因为可以生成默认赋值运算符并不意味着默认行为在逻辑上是正确的。
The asker's problem is with the std::remove
portion of the line.提问者的问题在于该行的
std::remove
部分。 std::remove
needs a way to compare the Request
s in requests
to request
to see which Request
s match and need to be removed. std::remove
需要一种方法来比较requests
与request
中的Request
以查看哪些Request
匹配并需要删除。 std::remove
uses the ==
operator to perform the comparison. std::remove
使用==
运算符来执行比较。 The C++ compiler will not generate an equality operator for you because the odds of getting it wrong are far too high. C++ 编译器不会为您生成相等运算符,因为出错的几率太高了。 For example, Which members are to be compared?
例如,要比较哪些成员? All of them?
他们全部? One of them?
其中之一? First name and last name only?
只有名字和姓氏? Student ID?
学生卡? Bank account number?
银行帐号?
So we add a所以我们添加一个
bool operator==(const Request& lhs, const Request& rhs)
{
return /* comparison logic*/;
}
to do the heavy lifting.做繁重的工作。
See What are the basic rules and idioms for operator overloading?请参阅运算符重载的基本规则和习惯用法是什么? for further details and general wisdom about operator overloading.
有关运算符重载的更多详细信息和一般知识。
The code compiles when defining operator==定义 operator== 时代码编译
class Request
{
public:
bool operator==(const Request &other) const {return true;}
};
Best regards.此致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.