我有一个项目要比较两个堆栈的内容,但我在使用此功能时遇到问题。我相信我已经正确完成了程序的其余部分。我在 B.myCharacters.empty()(表达式必须具有类类型)和 B==B.myCharacters(没有运算符“==”匹配这些操作数)上出现错误。
bool CharStack::IsEqual(CharStack & B)
{
if (B.empty())
{
cout << "Stack is empty" << endl;
return false;
}
else if (B.myCharacters.empty())
{
cout << "Stack is empty" << endl;
return false;
}
else if (B == B.myCharacters)
return true;
}
如有任何帮助,我们将不胜感激。
这是标题和驱动程序。它们是老师为这个项目提供的,我不能更改它们,即使有更好的方法。
#include <iostream>
#include <string>
using namespace std;
const int STACK_CAPACITY = 128;
typedef char StackElement;
class CharStack
{
private:
char myCharacters[STACK_CAPACITY]; // STL stack of chars.
int myTop;
public:
CharStack();
bool empty();
void push(const StackElement & value);
StackElement top() const;
void pop();
void StringToStack(const string & inStr);
friend ostream & operator <<(ostream & out, const CharStack & CS);
CharStack Reverse();
bool IsEqual(CharStack & B);
};
司机
#include <string>
#include <cassert>
#include "Header.h"
using namespace std;
//introduces namespace std
int main(void)
{
ifstream in;
string fileName, line[30];
int i = 0;
CharStack N, M, P;
cout << "Enter file name for palindrome check: ";
cin >> fileName;
in.open(fileName.c_str());
assert(in.is_open());
while (!in.eof())
{
getline(in, line[i]);
N.StringToStack(line[i]);
cout << N << endl;
P = N;
M = N.Reverse();
if (P.IsEqual(M))
cout << "This line is a palindrome line" << endl;
else
cout << "This line is not a palindrome line" << endl;
i++;
}
cout << "\nProgram ended normally.\n";
system("pause");
}
最佳答案
假设您的 CharStack
在内部将字符保存在 std::string
中,即
class CharStack
{
std::string myCharacters; // internal data
public:
bool IsEqual(CharStack const&) const;
/* ... */
};
和IsEqual()
应该返回如果两个堆栈相同,那么实现很简单
bool CharStack::IsEqual(CharStack const&other) const
{
return myCharacters == other.myCharacters;
}
这将一个空堆栈和一个非空堆栈比较为不相等,但将两个空堆栈比较为相等,这可以说是正确的行为。如果你想让两个空栈不相等你可以
bool CharStack::IsEqualNonEmpty(CharStack const&other) const
{
return !myCharacters.empty() && myCharacters == other.myCharacters;
}
另请注意关键字 const
的各种用法。
关于c++ - 比较堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48963573/