为什么我不能比较 IF 语句中的三个不同值?.CPP
Why cant I compare between three different values in IF statement? CPP
假设我有下一个代码示例:
std::string MyString("Michael");
std::cout << (str.find_first_of('=') == str.find_last_of('=') == str.npos);
前面的代码应该给我 1,因为来自 str 成员函数的前两个返回值将是:
4294967295
这也是 npos 的价值。但相反,"0"正在屏幕上打印。
另一件奇怪的事情是,下一个代码:
std::string MyString("Michael");
std::cout << (str.find_first_of('=') == str.find_last_of('=')) << std::endl;
std::cout << (str.find_last_of('=') == str.npos) << std::endl;
为两个输出打印"1"。
有人可以解释为什么我不能像上面那样比较 3 个值?
你不能像这样链接布尔比较(好吧,你可以,但它并没有像你想象的那样)。它需要是:
std::cout << (str.find_first_of('=') == str.npos && str.find_last_of('=') == str.npos);
即由逻辑 AND 连接的两个比较。
(str.find_first_of('=') == str.find_last_of('=') == str.npos)
这基本上是:
(true == str.npos);
这是false
,因此,给你0
.
更改
std::cout << (str.find_first_of('=') == str.find_last_of('=') == str.npos);
// compares the result of a==b with c
自
std::cout << (str.find_first_of('=') == str.find_last_of('=') && str.find_last_of('=') == str.npos);
// ensures a == b && b == c
另外,您可能自己几乎知道答案(只是试图将事情联系起来)-
std::cout << (str.find_first_of('=') == str.find_last_of('='))
给你1
,你当然知道str.npos = 4294967295
简化事情 -
std::cout << (str.find_first_of('=') == str.find_last_of('=') == str.npos)
更改为
std::cout << (1 == 4294967295)
并导致0
.
注意 - 特别是以first_of
和last_of
比较为例,因为==
遵循从左到右的关联性。尽管在您的情况下,无论如何结果都是一样的。
相关文章:
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 在 2D 向量中使用第三个 [ ] 有什么意义?
- 如何通过按下第三个窗口中的按钮,将QString从一个窗口获取到另一个窗口
- 有没有办法简单地从 GPU 调用多个 cpp 输出文件?
- 如何知道n!是否可以表示为三个连续数字的乘法?
- 我有三个 getline,但是一旦编译,输入就太多了
- 我遇到了黑客排名中的问题"TWO STRINGS"的三个测试用例的分段错误。原因是什么?
- 有没有更好的方法对C++中的三个整数进行排序?
- 将两个 cpp 文件合并为一个 cpp 文件
- 如何将代码划分为多个.cpp文件 C++.
- 如何检查第三个 API 是否在 Linux 中为 c/c++ 程序创建了一个新线程?
- 在两个.cpp文件之间定义全局类/结构指针
- 为什么 getch 在按下函数或箭头键时返回三个值?
- 使用三个数字比较器进行排序
- 我想在C++代码中比较这三个术语
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- 我该如何编码,使计算机知道两个名称条目和三个名称条目之间的区别
- 为什么我不能比较 IF 语句中的三个不同值?.CPP
- 关于实施其中之一的CPP,这三个规则究竟是什么?
- 如何在三个不同的.cpp文件中使用函数