【问题标题】:Need Help Using "Sort" Within My Program在我的程序中使用“排序”需要帮助
【发布时间】: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


【解决方案1】:

sort 期望可以迭代的东西。

你的工作示例有

 char input[]

(一个字符数组)

您的非工作示例删除了数组语法并使其成为普通字符

 char input

当您尝试这样做时:

 sort(input, input + 4, &compareprec)

在工作情况下,因为您提供了一个数组,所以您告诉它从输入的开头迭代到 4 过去的位置。在非工作情况下,您告诉它从说“a”到“d”(即“a”+ 4)。

【讨论】:

  • 我尝试将其改回“char input[]”,但出现错误“错误:'input' 的存储大小未知”。
  • 在您的第一个示例中,输入被初始化为 C 样式字符串。编译器从此字符串推断输入的长度。因此,您需要在第二个示例中以相同的方式初始化 char 数组,或者在 [] 之间放置一个数字来指定长度。
【解决方案2】:

为什么你必须在第二个例子中对任何东西进行排序?您最多需要比较两个运算符,一个在堆栈顶部,一个在输入中。只需使用您的compareprec-函数并根据结果采取相应措施。

顺便说一句,为了让你的代码更漂亮,创建一个函数:

 bool is_operator(char s);

差点忘了告诉你,第二个例子int prec(char a)的版本不对,用第一个吧。

【讨论】:

    猜你喜欢
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多