我正在尝试按自定义数据类型 vector 的值删除 vector 元素。如果我使用 int
等简单数据类型而不是 hello
数据类型,它工作正常。
#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;
}
显示错误:
binary '==': no operator found which takes a left-hand operand of type 'hello' (or there is no acceptable conversion) vector_test
最佳答案
看起来你更想使用 remove_if
.x
成员为真。
vector_t.erase(std::remove_if(vector_t.begin(), vector_t.end(), [](const hello &h) { return h.x; }), vector_t.end());
for
循环和 if
条件不是必需的,因此不需要它们。
关于C++ - 按自定义数据类型 vector 的值删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50838368/