首页 > 解决方案 > 使用erase-remove-idiom从结构的向量中删除结构的元素

问题描述

我有一个结构向量,我想从具有特定值的向量中删除一个元素。我知道如何做到这一点,例如使用擦除删除的 int 值向量,但现在确定如何为结构:

#include <algorithm>
#include <string>
#include <iostream>

using namespace std;

struct file_line{
    string pcounter;
    int optype;
};

int main() {
    vector<file_line> v = {file_line{"aa",1}, file_line{"bb", 2}, file_line{"cc", 5}, file_line{"ddd", 12}};

    v.erase(remove(v.begin(),v.end(),file_line{"cc",5} ), v.end());
    
    return 0;
}

这是我收到的错误:

/usr/include/c++/7/bits/predefined_ops.h:241:17: error: no match for ‘operator==’ (operand types are ‘file_line’ and ‘const file_line’)
  { return *__it == _M_value; }

标签: c++vectorerase-remove-idiom

解决方案


正如错误消息所说,编译器不知道如何比较两个file_line对象。您可以通过以下方式自己提供此比较:

bool operator==(file_line const & a,file_line const & b)
{
    return a.pcounter == b.pcounter and a.optype == b.optype;
}

这是一个演示


推荐阅读