C++ - 按自定义数据类型向量的值删除元素



我正在尝试按自定义数据类型向量的值删除向量元素。如果我使用简单的数据类型(如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;
}

它显示一个错误:

二进制"==":未找到采用类型为"hello"的左侧操作数(或没有可接受的转换(vector_test

运算符

看起来您想在.x成员为真的地方使用remove_if

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

for循环和if条件不是必需的,不需要这样。

remove尝试查找与您传递给它的任何元素相的所有元素。如果不告诉编译器如何将hello对象与整数i值进行比较,则编译器无法执行此操作。

您可能想做的是,如果向量满足你的条件,则只删除向量的第 i 个元素:

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!
}
}

最惯用的方法是使用 acgraig5075 答案中所示的std::remove_if

它显示一个错误:

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

您可以为您的类提供明显缺少的运算符==,这将解决问题:

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

您的删除/擦除应如下所示:

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

演示:https://ideone.com/E3aV76

最新更新