为什么将三个变量与 == 一起比较会计算为 false?
Why comparing three variables together with == evaluates to false?
以下程序的输出是"它们不相等",但我希望"它们是相等的",因为三个比较变量(x
、y
和z
(是相等的。为什么?
#include <iostream>
int main()
{
int y, x, z;
y = 3;
x = 3;
z = 3;
if (x == y == z)
{
std::cout << "they are equaln";
}
else
{
std::cout << "they are not equaln";
}
}
这是因为计算表达式和类型的方式。
让我们评估最左边的==
x == y ...
此计算结果为 true。让我们重写表达式:
// x == y
if (true == z) {
// ...
}
true
是一个布尔值。布尔值不能直接与int
进行比较。必须从布尔值转换为整数,结果1
(是的,true
==1
(。让我们将表达式重写为其等效值:
// true
if (1 == z) {
// ^--- that's false
}
但z
不等于1
。这句话是假的!
相反,您应该将两个布尔表达式分开:
if (x == y && y == z) {
// ...
}
现在还有一些实用的 C++17 应用程序。无需 SFINAE。
//----------------------------------
// constexpr lambda requires C++17
auto eq3 = [] (auto v1, auto v2, auto v3) constexpr -> bool
{
return ( v1 == v2 ) && ( v2 == v3 );
};
用法很简单,但完全编译
constexpr auto same_ = eq3(42,42,42);
std::bool_constant< eq3(42,42,42) > twins_ ;
对于比较整个值序列,概念是相同的,即兴更复杂。
template<typename ... T>
constexpr bool all_equal ( const T & ... args_ )
{
if ((sizeof...( args_) ) < 2) return true;
// for non recursive version
const auto il_ = { args_ ... };
// compare them all to the first
auto first_ = *(il_.begin()) ;
// assumption
bool rezult_{ true };
for ( auto && elem_ : il_) {
// yes I know, first cycle compares first_ to itself ...
rezult_ = rezult_ && ( first_ == elem_ );
// short circuit-ing
if (!rezult_) break;
}
return rezult_;
};
"只是"一个函数,编译时,再次没有可变参数模板欺骗。
bool_constant< all_equal(42,42,42,42,42,42,42) > same_ ;
cout << endl << boolalpha << same_() ;
bool_constant< all_equal(42,43,44,45,46,47) > not_same_ ;
cout << endl << boolalpha << not_same_() ;
强制性魔杖盒在这里。
ps:有点可预测all_equal
不会使用最新的CL(也称为MSVC或Visual Studio(进行编译。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么比较运算符如此快速
- 我可以使用 g++ 进行三种比较 (<=>) 吗?
- 如何将enable-if与模板参数和参数包一起使用
- 如何将PERF_AMPLE_READ与mmap一起使用
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 比较字符数组
- 将模板化的类型与C++中的某些类/类型进行比较
- C++自定义比较函数
- 将 std::set 与基于键的比较器一起使用
- 不能将重载比较运算符与 Catch 测试一起使用
- gtest 期望无序元素与自定义比较器/匹配器一起使用
- 为什么将三个变量与 == 一起比较会计算为 false?
- 如何在 C++11 中将 std::max 与自定义比较器一起使用?
- 字符串比较在与变量一起使用时给出不同的输出
- 为什么set_symmetric_difference无法与比较器一起使用
- 将字符比较在一起
- 如何将unordered_set与比较功能一起使用
- 我可以在 IF 语句中将比较链接在一起吗?
- 如何使用自定义比较器函数将所有字谜组合在一起