用c++来实现:输入1行字符串,将字符串中的字符按升序排序后输出, 要求排序过程通过一个函数实现

如题所述

#include<iostream>
#include <string>
#include<windows.h>
using namespace std;
void sort(string& a)//定义排序函数,用冒泡排序法
{
int m = a.length();
int n = m-1;
for(int i=0 ; i < n; i++)
{
for(int j=0;j< m-1;j++)
{
if(a[j]>a[j+1])
{
char temp;
temp = a[j];
a[j] = a[j+1];
a[j+1]=temp;
}

}
m--;
}

}
int main()
{
string a;
cout<<"输入字符串a:"<<endl;
cin>>a;
sort(a);
cout<<"排序结果为:"<<a<<endl;
system("pause");
return 0;

}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-05-04
假定一行就是一个字符串
按第一个字母从小到大排序,第一个字母相同则看第二个

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
string s;
vector<string> a;
fstream fin("1.txt", ios::in),fout("3.txt", ios::out);
if(!fin)
{
cerr << "cannot open!" << endl;
return -1;
}
while(!fin.eof())
{
getline(fin,s,'\n');
a.push_back(s);
}
sort(a.begin(),a.end());
for(vector<string>::iterator t = a.begin(); t != a.end(); t++)
fout << *t << endl;
fin.close();
fout.close();
return 0;
}