C++在vector中查找匹配所有成员的struct时报模板推导错误如何解决
错误原因
- 缺少必要头文件:
std::find函数定义在<algorithm>头文件中,当前代码未引入该头文件。 - 自定义结构体无匹配的相等比对逻辑:
std::find默认使用==运算符判断容器元素与目标值是否相等,你定义的vlan结构体没有重载==运算符,编译器无法推导对应的比对实现,因此触发模板参数推导/替换失败的错误。
解决方法
- 首先在头文件引入区域新增
<algorithm>头文件:
#include <algorithm>
- 给
vlan结构体重载==运算符,实现你需要的全成员匹配逻辑:
如果使用C11~C17版本,手动实现比对逻辑:
struct vlan { int vlanId; bool status; bool operator==(const vlan& other) const { // 两个vlan对象的所有成员相等才判定为相等 return vlanId == other.vlanId && status == other.status; } };
如果使用C++20及以上版本,可以直接用默认生成的全成员比对实现,写法更简洁:
struct vlan { int vlanId; bool status; bool operator==(const vlan&) const = default; };
修复后的完整可运行代码
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct vlan { int vlanId; bool status; bool operator==(const vlan& other) const { return vlanId == other.vlanId && status == other.status; } }; vector<vlan> vlanTable; int main(){ // 测试用:给容器添加测试元素验证查找逻辑 vlanTable.push_back({1, true}); vlanTable.push_back({2, false}); vlan tmp; tmp.status = true; tmp.vlanId = 1; vector <vlan>::iterator flag = find(vlanTable.begin(), vlanTable.end(), tmp); if ( flag != vlanTable.end()){ cout<<"found"<<endl; } else cout<<"not found"<<endl; return 0; }
内容的提问来源于stack exchange,提问作者Minh Pham
相关产品推荐
相关产品推荐

