比较双精度堆栈导致Always Equal
Comparing Stacks of Doubles resulting in Always Equal
我试着比较两个堆栈,看看它们是否相等。不幸的是,这段代码使得我所有的比较都表明堆栈是相等的,即使堆栈不是相等的。
Stack_implementation.cpp
snippet:
int DoubleStack::operator==(DoubleStack& rhs)
{
int equal = 1;
for (int i = 0; i <= tos; i++) //tos is the top of the stack indicator
{ //it tells how big the stack is
if (data[i] != rhs.data[i])
{
equal = 0;
break;
}
}
return equal;
}
main.cpp
相关片段:
{
cout << "Comparing stacks..." << endl;
if (stack1 == stack2)
cout << "stack1 = stack2." << endl;
else
cout << "stack1 != stack2." << endl;
}
输出总是stack1 = stack2
有人知道怎么回事吗?
第一个检查应该是堆栈的大小;如果大小不相同,堆栈就不能相等。所编写的代码可能超出其中一个堆栈的末端。
你也可以尽快返回,只要你发现一个不同的项目。没有必要继续循环。
bool DoubleStack::operator==(DoubleStack& rhs)
{
if (tos != rhs.tos) {
return false;
}
for (int i = 0; i <= tos; i++) //tos is the top of the stack indicator
{ //it tells how big the stack is
if (data[i] != rhs.data[i])
{
return false;
}
}
return true;
}
相关文章:
- 如何使用"equal to"以外的评估编写开关语句
- C++有"not equal compare and exchange"或"fetch add on not equal"吗?
- 为什么 std::equal 模板由两个类参数化?
- C++20概念中的"equal"概念
- 如何在Visual Studio 2019中修复"[member variable that is a vulkan struct] is uninitialized. Always initiali
- 使用代码调整删除"comparison is always false"警告
- 符合要求的编译器应该能够优化哪些指针比较以"always false"?
- 使用'equal to'符号初始化期间的内存
- QPixmap,如何确保它是'always on top'
- 在Linux上使用QT,有没有办法禁用"Always on Top"?
- equal()是否默认包含在全局命名空间中
- 在 C 族中,在一个循环中,为什么"less than or equal to"比"less than"符号更受欢迎?
- std::具有用户定义类的equal函数
- 我怎样才能写得"if not greater than or equal to some value"雄辩?
- (false - NOT (0)) is equal to 1?
- "Condition is always true"当我知道它不是
- 为什么"the adress of bool will always evaluate as true"会在这里?
- 是 'char* p=0;std::equal(p,p,p)' 根据C++标准明确定义
- 为什么C++ STL 容器使用 "less than" 运算符<而不是 "equal equal" 运算符== 作为比较器?
- 比较双精度堆栈导致Always Equal