简体   繁体   中英

C++ - Removing element by value of custom data type vector

I am trying to delete vector element by value for custom data type vector. It works fine If I use the simple data type like int etc instead of hello data type.

#include <iostream>
#include <vector>
#include <algorithm>

class hello
{

public:
    hello() {
        x = false;
    }
    bool x;
};

int main() {

   hello f1;
   hello f2;
   hello f3;

   std::vector <hello> vector_t;

   vector_t.push_back(f1);
   vector_t.push_back(f2);
   vector_t.push_back(f3);

   for (unsigned int i = 0; i < vector_t.size(); i++)
       {
       if (vector_t[i].x)
       {
            vector_t.erase(std::remove(vector_t.begin(), vector_t.end(), i), vector_t.end());
        }
    }

    return 0;
}

It shows an error:

binary '==': no operator found which takes a left-hand operand of type 'hello' (or there is no acceptable conversion) vector_test

Looks like you want to rather use remove_if where the .x member is true.

vector_t.erase(std::remove_if(vector_t.begin(), vector_t.end(), [](const hello &h) { return h.x; }), vector_t.end());

The for loop and if condition aren't necessary, they're not needed this way.

remove tries to find all elements that compare equal to whatever you passed to it. If you do not tell the compiler how to compare hello objects with the integer i value, it cannot do that.

What you probably wanted to do was to just remove the i-th element of the vector if it satisfies your criterion:

for (unsigned int i = 0; i < vector_t.size(); i++)
{
    if (vector_t[i].x)
    {
        vector_t.erase(vector_t.begin() + i);
        --i; // The next element is now at position i, don't forget it!
    }
}

The most idiomatic way would be using std::remove_if as shown in acgraig5075's answer.

It shows an error:

binary '==': no operator found which takes a left-hand operand of type 'hello' (or there is no acceptable conversion) vector_test

You can provide the obviously missing operator == for your class which will solve the issue:

bool operator==(hello const &h)
{
    return this->x == h.x;
} 

Your remove/erase should look like this though:

vector_t.erase(std::remove(vector_t.begin(), vector_t.end(), vector_t[i]), vector_t.end());

Demo: https://ideone.com/E3aV76

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