需求:
需要查找 vector 中某个元素,根据 struct 或者 class 类型中的某个字段。
根据ID查找
定义数据结构
#pragma once
//重载运算符测试
struct MyOverloadOperatorStruct {
int x, y;
char id;
//判断e 是否相等 根据 x,y 字段判断
bool operator == (const MyOverloadOperatorStruct& e) {
return (this->x == e.x) && (this->y == e.y);
}
//查找数值p是否与x相等
bool operator == (const int& p) {
return (this->x == p);
}
//查找字符str是否与id相等
bool operator==(const char& str) {
return (this->id == str);
}
};
测试根据id查找,根据x,y 字段判断两个两个结构体是否相等
void operatorTest() {
MyOverloadOperatorStruct str1;
str1.x = 1;
str1.y = 2;
str1.id = 'a';
MyOverloadOperatorStruct str2;
str2.x = 3;
str2.y = 5;
str2.id = 'b';
MyOverloadOperatorStruct str3;
str3.x = 1;
str3.y = 2;
str3.id = 'd';
vector<MyOverloadOperatorStruct> arr = { str1,str2 };
vector<MyOverloadOperatorStruct>::iterator itr = find(arr.begin(), arr.end(), 'b');
if (str1 == str3) {
cout << "根据x,y 判断两个结构体相等" << endl;
}
}
我是这样调用查找的:
vector<MyOverloadOperatorStruct>::iterator itr = find(arr.begin(), arr.end(), "b");
遇到的坑:
严重性 代码 说明 项目 文件 行 禁止显示状态
错误 C2678 二进制“==”: 没有找到接受“MyOverloadOperatorStruct”类型的左操作数的运算符(或没有可接受的转换) E:\personal\code\my_c_cplusplus_project\cPulsPlusTestProject\out\build\x64-Debug\cPulsPlusTestProject C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\xutility 5307
可能的原因:
传入的类型与定义的类型不一致
传入字符串,定义的id 类型是字符
正确用法:
vector<MyOverloadOperatorStruct>::iterator itr = find(arr.begin(), arr.end(), 'b');
使用字符串----------------------------------------------------------》
#pragma once
//重载运算符测试
struct MyOverloadOperatorStruct {
int x, y;
char id;
std::string name;
//判断e 是否相等 根据 x,y 字段判断
bool operator == (const MyOverloadOperatorStruct& e) {
return (this->x == e.x) && (this->y == e.y);
}
//查找数值p是否与x相等
bool operator == (const int& p) {
return (this->x == p);
}
//查找字符str是否与id相等
bool operator==(const char& str) {
return (this->id == str);
}
bool operator==(const std::string& na) {
return (this->name == na);
}
};
void operatorTest() {
MyOverloadOperatorStruct str1;
str1.x = 1;
str1.y = 2;
str1.id = 'a';
str1.name = "大";
MyOverloadOperatorStruct str2;
str2.x = 3;
str2.y = 5;
str2.id = 'b';
str2.name = "小";
MyOverloadOperatorStruct str3;
str3.x = 1;
str3.y = 2;
str3.id = 'd';
str3.name = "多";
vector<MyOverloadOperatorStruct> arr = { str1,str2 };
vector<MyOverloadOperatorStruct>::iterator itr = find(arr.begin(), arr.end(), 'b');
if (str1 == str3) {
cout << "根据x,y 判断两个结构体相等" << endl;
}
vector<MyOverloadOperatorStruct>::iterator itr1 = find(arr.begin(), arr.end(), "大");
if (itr1->name == "大") {
cout << "找到名称为大的x: "<< itr1->x << endl;
}
}
运行结果: