简体   繁体   中英

vector::erase fails with invalid operands to binary expression (T and const T)

I have a Class called Request like this,

class Request {};

I store objects of this type in a global vector called,

std::vector<Request> requests;

I initialize the object using,

auto &request = requests.emplace_back();

Now, I attempt to delete the object using the reference provided by emplace_back like this,

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. 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. 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 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 uses the == operator to perform the comparison. The C++ compiler will not generate an equality operator for you because the odds of getting it wrong are far too high. 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==

class Request
{
public:
  bool operator==(const Request &other) const {return true;}
};

Best regards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM