c++ - 使用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; }
解决方案
正如错误消息所说,编译器不知道如何比较两个file_line
对象。您可以通过以下方式自己提供此比较:
bool operator==(file_line const & a,file_line const & b)
{
return a.pcounter == b.pcounter and a.optype == b.optype;
}
这是一个演示。
推荐阅读
- c - 为什么 memset 不设置所有内存?
- python - Python中的决策树桩
- google-bigquery - 通过命令提示符/计划任务验证 bigquery 是否成功上传
- javascript - JS(jquery)自动搜索不拉 MySQL 数据
- c# - 如何加快 WinForms 中的自动完成
- c# - ASP.NET Core 和 Visual Studio 中的模型类
- javascript - 尝试从 API 解析和存储 JSON 数据时如何知道目标是什么
- docker - 在 GitLab 中使用 ElasticSearch,如果 ES Container 宕机了怎么办?
- android - 无法解析“:app@debug/compileClasspath”的依赖关系:无法解析com.android.volley:volley:1.1.1
- python - Python 2d 数组布尔减少