c++ - 嵌套的 if-else 不适用于自定义结构 c++

标签 c++ algorithm c++11 structure

我有一个自定义数据结构 date在 C++11 中:

struct date {
   int day;
   int month;
   int year;
};

我想比较两个 date s 并为其编写函数:

int compare_dates(date a, date b) {
    int result = 0;

    if (a.year < b.year) {
        result = -1;
    } else if (a.year == b.year) {
        if (a.month < b.month) {
            result = -1;
        } else if (a.month == b.month) {
            if (a.day < a.day) {
                result = -1;
            } else if (a.day > a.day) {
                result = 1;
            }
        } else {
          result = 1;
        }
    } else {
        result = 1;
    }

    return result;
}

但是这个函数不能正常工作。我花了很多时间调试它,并在以下代码部分发现了一些问题:

} else if (a.month == b.month) {
    if (a.day < a.day) {
        result = -1;
    } else if (a.day > a.day) {
        result = 1;
    }
} else {
  result = 1;
}

调试时有两张截图,first} else if (a.month == b.month) {second当我在调试器中单击下一行 时。所有输入都会发生这种情况。为什么调试器没有输入 if (a.day < a.day) {result = 1;每次?

最佳答案

尝试

if (a.day < b.day) {
    result = -1;
} else if (a.day > b.day) {
    result = 1;
}

代替

if (a.day < a.day) {
    result = -1;
} else if (a.day > a.day) {
    result = 1;
}

两个测试a.day < a.daya.day > a.day永远是假的,所以result = -1result = 1永远不会被执行。

我想编译器优化代码如下

} else if (a.month == b.month) {
} else {
  result = 1;
}

关于c++ - 嵌套的 if-else 不适用于自定义结构 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40691952/

相关文章:

c++ - 如何将 QString 转换为 std::string?

algorithm - 二维数组的 Rabin Karp 算法

algorithm - 证明斐波那契递归算法的时间复杂度

c++ - Visual C++ 为什么 std::move 崩溃

c++ - Clang 为直觉上应该等效的表达式提供非常不同的性能

c++ - 简单的 C++ 代码链接器错误

algorithm - 对于小数,最有效的整数 n 次根算法是什么?

c++ - 此 c++11 lambda 代码是否调用未定义的行为?

c++ - 为什么 std::to_string 的实现会创建一个 4 倍于类型大小的缓冲区?

c++ - 仅在添加第二个项目后才出现第一个项目的编译错误