谁能告诉我哪里出错了。我在提交代码时遇到运行时错误,但运行了给定的测试用例?
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?
这是给定的问题:
给定一个字符串 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
算法
输出
特罗姆利加
对于初学者来说,变量 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
这是给定的问题: 给定一个字符串 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
算法
输出
特罗姆利加
对于初学者来说,变量 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