【问题标题】:Can someone tell me where I went wrong. I am getting a runtime error when I submit the code, but runs for given test cases?谁能告诉我哪里出错了。提交代码时出现运行时错误,但针对给定的测试用例运行?
【发布时间】:2021-07-28 00:25:22
【问题描述】:

这是给定的问题: 给定一个字符串 S,您必须按字典顺序对字符串的字符进行排序。 注意 - 不要使用内置的排序功能。

#include <bits/stdc++.h>
#include <string>
  using namespace std;
  
  int main()
  {
    //write your code here
    int t;
    cin>>t;
    while(t--)
    {
      int n,temp,min,i,j;
      string s,text;
      cin>>s;
      n=s.length();
      int arr[n];
      for(int i=0;i<n;i++)
      {
        arr[i]=int(s[i]);
      }
      for(i=0;i<n;i++)
        {       
            for(j=i+1;j<n;j++)
            {
                if(arr[i]<arr[j])
                {
                    temp  =arr[i];
                    arr[i]=arr[j];
                    arr[j]=temp;
                }
            }
        }
      for(int l=0;l<n;l++)
      {
        text[l]=arr[l];
        cout<<text[l];
      }
      
      cout<<endl;
    }
    return 0;
  }

输入

1

算法

输出

特罗姆里加

【问题讨论】:

  • 提示:使用std::vectorpush_back() 而不是像int arr[n] 这样的非标准可变长度数组。
  • s[i]-0 应该做什么?这是对数组中的单个字符进行排序吗?如果是这样,solved problem。只是std::sort 字符串本身。简单。完成。
  • text 是一个空字符串,除text[0] 之外的任何字符串都超出范围。再一次,你做的比必要的要多得多。而不是从arr[l]复制到text[l]然后循环打印text[l],只需执行std::cout &lt;&lt; arr;
  • 你为什么用那个代替对sort的调用?之前的代码太复杂了,现在更糟了……

标签: c++ string sorting for-loop nested-loops


【解决方案1】:

对于初学者,变量t 应声明为具有无符号整数类型。否则用户可以输入负数。

在你的程序中声明的可变长度数组,例如这个数组

int arr[n];

不是标准的 C++ 功能。

这个for循环

  for(int l=0;l<n;l++)
  {
    text[l]=arr[l];
    cout<<text[l];
  }

调用未定义的行为,因为对象text 为空。所以你不能使用下标操作符来改变对象。

要按字典顺序对字符串进行排序,不需要使用辅助数组,

对字符串s的元素进行就地排序。

您在没有辅助数组的情况下对字符串进行排序的方法如下面的演示程序所示。

#include <iostream>
#include <string>

int main() 
{
    std::string s( "ABCDEFGHIJ" );
    
    std::cout << s << '\n';

    for ( std::string::size_type i = 0, n = s.length(); i < n; i++ )
    {
        for ( std::string::size_type j = i + 1; j < n; j++ )
        {
            if ( s[i] <  s[j] )
            {
                char c = s[i];
                s[i] = s[j];
                s[j] = c;
            }
        }
    }

    std::cout << s << '\n';
    
    return 0;
}

程序输出是

ABCDEFGHIJ
JIHGFEDCBA

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    相关资源
    最近更新 更多