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

标签 c++ vector

我正在尝试按自定义数据类型 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/

相关文章:

c++ - 如何从可执行文件的多重/双重代码签名中检索信息

c++ - 迭代多个嵌套 vector

C++ 字符串与 vector <char>

matlab - 当期望值向量时,操作返回标量值

c++ - 何时使用不声明类但具有函数定义的头文件

c++ - 打印指针变量的地址

c++ - 关于 shared_ptr

c++ - 回推到静态 vector 中的 vector

c++ - 是否有任何 C++ 静态分析工具来检测 vector 的潜在错误

c++ - 如何使用构造函数初始化另一个类中的对象?