【问题标题】:How do I compare chars (or strings) using void functions, also comparing chars that were taken from a struct array如何使用 void 函数比较字符(或字符串),还比较从结构数组中获取的字符
【发布时间】:2013-10-09 16:55:54
【问题描述】:

我需要比较以下结构中包含的不同类型的数据:

struct Person{
    string surname;
    char BType;
    string organ;
    int age;
    int year, ID;
} Patient[50], Donor[50];

这些结构正在使用以下文件进行初始化:

Patients 3
Androf B kidney 24 2012
Blaren O kidney 35 2010
Cosmer A heart 35 2007

...其中的字段分别是 surname、BType、organ、age、year。

如果我想比较Patient[1]BTypeDonor[1]BType,我该怎么做?

【问题讨论】:

  • 你试过Patient[1].BType == Donor[1].BType吗?发生了什么?

标签: c++ arrays data-structures struct void


【解决方案1】:

如果我理解正确,您有一个包含多个不同类型成员的结构,并且您正在寻找一种方法来比较该结构的实例。

它可能如下所示:

struct X {
    std::string s;
    char c;
    int i;
    bool operator==(const X& ref) {
        return s == ref.s && c == ref.c && i == ref.i;
    }
    bool operator!=(const X& ref) {
        return !this->operator==(ref);
    }
};

可能的用法:

X x1, x2;
x1.s = x2.s = "string";
x1.c = x2.c = 'c';
x1.i = x2.i = 1;
if (x1 == x2)
    std::cout << "yes";
x1.s = "string2";
if (x1 != x2)
    std::cout << " no";

输出yes no,因为起初所有成员都相等,但后来的字符串不同。


但是如果你只需要比较特定的成员,直接访问和比较它们(不需要重载operator==):

if (Patient[1].BType == Donor[1].BType) {
    ...
}

【讨论】:

  • 哇...不敢相信我没有想到这一点。非常感谢,帮了大忙。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-06
  • 1970-01-01
相关资源
最近更新 更多