【问题标题】:C++ Comparing two structures to show what are the differenceC ++比较两个结构以显示有什么区别
【发布时间】:2014-11-06 23:14:55
【问题描述】:

我有两个这样的结构

struct Activity {
int id;
string Description;
int parameter1;
int parameter2;
int parameter3;
int parameter4;
etc...
}

Activity A1;
A1.id=0;
A1.parameter1=50;

Activity A2;
A2.id=0;
A2.parameter1=55;

我想比较它们,以显示哪些成员不同? 在这种情况下,类似于:

paameter1 不同...

谢谢

【问题讨论】:

  • if (A1.parameter1 != A2.parameter1) ...
  • 你有没有尝试过?展示你的尝试。
  • 我认为 OP 要求在 dotnet 或 java 中使用反射之类的东西。但遗憾的是,在 C/C++ 中没有这样的东西。

标签: c++


【解决方案1】:

最好的解决方案可能是在结构中编写公共方法,它将自己与通过参数传递的结构进行比较。

看起来像这样

struct Activity {
  int id;
  string Description;
  int parameter1;
  int parameter2;
  int parameter3;
  int parameter4;
  etc...

  public:
    bool compare(const Activity& param)
    {
      //...compare structs here like:
      if (id != param.id)
        //write something

      //etc...

      //at the end you can also return bool that indicates that structs are equal or not
      return true;
    }
}

这显然只适用于两个相同的类,除非您编写更多的比较方法,但比较两个不同的结构可能很困难。

还有其他方法可以比较两个变量(包括结构)。为此,可以使用 memcmp() 函数,但它不会直接告诉您哪些字段不同。

根据@Tony_D 所说的进行编辑。

【讨论】:

  • +1,但应该是bool compare(const Activity& param) const(如果麻烦跟踪布尔结果)。 const & 避免了 param 的不必要的缓慢复制构造,而尾部的 const 允许您使用该函数将 const Activity 对象与另一个对象进行比较。
  • 谢谢,因为我在结构中有很多成员,我不想为每个成员写一个比较。
  • @Gpouilly 你必须为每个写一个比较
猜你喜欢
  • 2011-01-14
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 2010-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多