【发布时间】:2011-01-24 01:24:49
【问题描述】:
我有一个简单的程序,它按优先顺序列出输入,只检查运算符并像这样对它们进行排序,“*/+-”:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int prec(char op)
{
if (op == '*' || op == '/') return 0;
return 1;
}
bool compareprec(char a, char b)
{
return prec(a) < prec(b);
}
int main()
{
char input[] = "+-/*";
cin >> input;
sort(input, input + 4, &compareprec);
cout << input;
}
我正在尝试在一个更复杂的程序中实现它,该程序使用堆栈来检查字母数字输入并进行中缀到后缀转换,排序如下所示:“9*9+9”到“9 9 9” * +”。比较复杂的程序如下:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int prec(char op)
{
if (op == '*' || op == '/' || op == '+' || op == '-') return 0;
return 1;
}
bool compareprec(char a, char b)
{
return prec(a) < prec(b);
}
int main()
{
stack<char> s;
char input;
while (cin.get(input) && input != '\n')
{
if (isalnum(input))
cout << input << " ";
else if (input == '(')
s.push(input);
else if (input == ')')
{
while (!s.empty() && s.top() != '(')
{
cout << s.top() << " ";
s.pop();
}
if(!s.empty())
s.pop();
else
cout << "ERROR: No Matching ( \n";
}
else if (s.empty() && input == '*'|| input == '/'|| input == '+'|| input == '-')
{
sort(input, input + 4, &compareprec); // Error Begins Here?
s.push(input);
}
else if (input == '*'||input == '/'||input == '+'|| input =='-')
while (!s.empty())
{
sort(input, input + 4, &compareprec); // More Errors Here?
cout << s.top() << "\n ";
s.pop();
s.push(input);
}
}
while (!s.empty())
{
cout << s.top() << " ";
s.pop();
}
}
但我不断收到一条错误消息:
error: no matching function for call to 'sort(char&, int, bool (*)(char, char))'
error: no matching function for call to 'sort(char&, int, bool (*)(char, char))'
我不知道为什么。我知道这可能是一件非常明显/愚蠢的事情,但我无法弄清楚。任何帮助,将不胜感激。提前致谢!
【问题讨论】:
-
你想在这些语句中排序什么?你没有排序任何有效的东西。
标签: c++ data-structures stack