如下程序,请问一下,怎样用模板对字符串惊醒排序?

#include<iostream>
#include<string>
using namespace std;

template <typename T>
T sort(T x[],int m){ //排序函数
int i,j,k;
T t;
for(i=0;i< m-1;i++)
{ k=i;
for(j=i+1;j< m;j++)
if(x[j]< x[k])
k=j;
if(k!=i)
{ t=x[i];x[i]=x[k];x[k]=t;}}return x[j];}

char sort(char x[],int m){ //字符排序重载
int i,j,k;
char t;
for(i=0;i< m-1;i++)
{ k=i;
for(j=i+1;j< m;j++)
if(x[j]< x[k])
k=j;
if(k!=i)
{ t=x[i];x[i]=x[k];x[k]=t;}}return x[j];}

//字符串数组的排序参考如下:
void sort(char str[20][20], int n) {
char a[20];
int i, j;
for (i = 0; i < n-1; i++) {
for (j = i ; j < n-1; j++)
if (strcmp(str[j], str[j + 1]) > 0) {
strcpy(a, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j+1], a);}return str[j];}

int main()
{
int a[]={19,25,56,45,15};
const int m=sizeof(a) / sizeof(*a);
sort(a,m);
for(int i=0;i<m;i++)
{cout<<a[i]<<"\t";}
cout<<"\n";

double b[]={1.0,5.2,4.3,6.2,2.5};
const int n=sizeof(b) / sizeof(*b);
sort(b,n);
for(int j=0;j<n;j++)
{cout<<b[j]<<"\t";}
cout<<"\n";

char c[]={'a','b','y','u','r'};
const int p=sizeof(c) / sizeof(*c);
sort(c,p);
for(int k=0;k<p;k++)
{cout<<c[k]<<"\t";}
cout<<"\n";

char s[][]={"hsdfkjf","dhfjsdfs"}
const int q=sizeof(s) / sizeof(*s);
sort(s[][],q);
for(int d=0;d<q;d++)
{cout<<s[j][j+1]<<"\t";}
cout<<"\n";

return 0;
}
额 那个主函数中的字符数组是我写的,有问题,好像!

30秒到达战场
浏览 132回答 2
2回答

烙印99

你好!问题挺多的,我给你改了!#include<iostream>#include<string>#include "string.h"using namespace std;template <typename T>T sort(T x[],int m){ //排序函数int i,j,k;T t;for(i=0;i< m-1;i++){ k=i;for(j=i+1;j< m;j++)if(x[j]< x[k])k=j;if(k!=i){ t=x[i];x[i]=x[k];x[k]=t;}}//return x[j];}char sort(char x[],int m){ //字符排序重载int i,j,k;char t;for(i=0;i< m-1;i++){ k=i;for(j=i+1;j< m;j++)if(x[j]< x[k])k=j;if(k!=i){ t=x[i];x[i]=x[k];x[k]=t;}}return x[j];}//字符串数组的排序参考如下:void sort(char str[20][20], int n) {char a[20];int i, j;for (i = 0; i < n-1; i++){for (j = i ; j < n-1; j++)if (strcmp(str[j], str[j + 1]) > 0){strcpy(a, str[j]);strcpy(str[j], str[j + 1]);strcpy(str[j+1], a);}//return str[j];}};int main(){int a[]={19,25,56,45,15};const int m=sizeof(a) / sizeof(*a);sort(a,m);for(int i=0;i<m;i++){cout<<a[i]<<"\t";}cout<<"\n";double b[]={1.0,5.2,4.3,6.2,2.5};const int n=sizeof(b) / sizeof(*b);sort(b,n);for(int j=0;j<n;j++){cout<<b[j]<<"\t";}cout<<"\n";char c[]={'a','b','y','u','r'};const int p=sizeof(c) / sizeof(*c);sort(c,p);for(int k=0;k<p;k++){cout<<c[k]<<"\t";}cout<<"\n";char s[][20]={"hsdfkjf","dhfjsdfs"};const int q=sizeof(s) / sizeof(*s);sort(s,q);for(int d=0;d<q;d++){cout<<s[d]<<"\t";}cout<<"\n";return 0;}

慕标琳琳

char&nbsp;s[][20]&nbsp;=&nbsp;{&nbsp;"hsdfkjf",&nbsp;"dhfjsdfs"&nbsp;};//第2维&nbsp;数组&nbsp;固定长度const&nbsp;int&nbsp;q&nbsp;=&nbsp;sizeof(s)&nbsp;/&nbsp;sizeof(*s);sort(s[0],&nbsp;strlen(s[0]));——>直接用模板sort(s[1],&nbsp;strlen(s[1]));for&nbsp;(int&nbsp;d&nbsp;=&nbsp;0;&nbsp;d<q;&nbsp;d++){&nbsp;&nbsp;&nbsp;&nbsp;cout&nbsp;<<&nbsp;s[d]&nbsp;<<&nbsp;"\t";}cout&nbsp;<<&nbsp;"\n";&nbsp;return&nbsp;0;
打开App,查看更多内容
随时随地看视频慕课网APP