c++ - 比较具有相同内容的两个不同结构的内容
问题描述
我有两个包含相同内容的结构,但它们并不相同。
struct ContainerType1 {
uint8_t isXYZ;
uint32_t foo;
uint8_t bar;
uint32_t nbOfItems;
typeXX ArryXXX[20]; };
struct ContainerType2 {
uint8_t isZ;
uint32_t x;
uint8_t y;
uint8_t z;
uint32_t nbOfItems;
typeXX ArryYY[20]; };
我只想比较这些结构中选定元素的对象。
bool CompareItems (ContainerType1 object1, ContainerType2 object2)
{
if(object1.nbOfItems != object1.nbOfItems or object1.isXYZ != object1.isZ)
{
return false;
}
for (int i=0; i< nbOfItems ; i++)
{
p1 = object1.ArryXXX;
p2 = object2.ArryYY;
if(p1.numberOfFoo != p2.numberOfBar)
return false;
if(p1.Foo.x != p2.Bar.x )
return false;
if(p1.a.y != p2.b.y )
return false;
}
return true;
}
**我没有能力改变/重新设计这些结构。我只能用它们来比较。
有一个更好的方法吗?就像将我想要比较的所有内容(整数和枚举)按顺序放在两个数组中并进行比较?
解决方案
正如问题下的评论所建议的那样,一种简单的方法是在其中一个结构下使用 == 运算符。
它看起来像这样:
struct ContainerType1 {
uint8_t isXYZ;
uint32_t foo;
uint8_t bar;
uint32_t nbOfItems;
typeXX ArryXXX[20];
bool operator == (const ContainerType2& other) const {
// everything you want to compare in here
// for example
if (isXYZ != other.isZ) return false;
// ...
}
};
struct ContainerType2 {
uint8_t isZ;
uint32_t x;
uint8_t y;
uint8_t z;
uint32_t nbOfItems;
typeXX ArryYY[20];
};
然后要比较它们,您可以简单地执行以下操作:
ContainerType1 a;
ContainerType2 b;
cout << (a == b) << endl;
推荐阅读
- objective-c - 在 Swift 中运行时创建 Objective-C 类的对象,符合 Objective-C 协议
- wso2 - Ballerina Facebook 连接器 - 无法创建 facebook 客户端
- c - C中的位运算符,int 021 vs 21?
- php - 对“如何使用 php/Mysql 存储本地日期时间和时区”感到困惑
- c# - 如何在 C# 中使用 JobStorage 获取所有 Hangfire 作业的列表?
- html - 滚动条 仅使用 CSS 的所有分辨率的免费网站布局
- angular - Angular Dynamic表单表单控件名称被清除
- java - 为什么在设置之前调用构造函数方法
- c++ - C++ 编译器是否可以优化用于将函数结果传递给另一个函数的虚拟变量的使用?
- schema - Shopify 部分架构未显示在管理员中