这个东西之前方向走错了,走了4天半也没做出来,被导师骂到怀疑人生。终于,我换了个方法,尼玛,终于啊。我都要哭了。
代码若有待改进,望指教。
#include <iostream>
#include <vector>
#include <string>
#define _CRT_SECURE_NO_WARING
using namespace std;
int main()
{
void sort_bubble(char *x, int n);//形参为地址
void print(char *x, int n);
vector<char> pInstr;
cout << "Please enter characters:" << endl;
string str;
cin >> str;
int n = str.length(); //获取输入的字符串长度
cout << "there are " << n << " elements in the sequence." << endl;
const char *TempInStr = str.c_str();//把string转换成char指针或者const char *TempInStr = str.data();
for (int i = 0; i<n; i++) //将输入的字符串赋给vector变量
{
pInstr.push_back(TempInStr[i]);
}
int length = pInstr.size();
char *p;
p = &pInstr[0];
sort_bubble(p, length);
print(p, length);
pInstr.swap(vector<char>(length));
//释放内存
return 0;
}
void sort_bubble(char *x, int n) //首地址和字符个数
{
int i, j;
for (j = 0; j < n - 1; j++) //0~n-2 共n-1次比较
for (i = 0; i < n - 1 - j; i++)
if (*(x + i) >= *(x + 1 + i))
{
int temp = *(x + i + 1);
*(x + i + 1) = *(x + i);
*(x + i) = temp;
}
}
void print(char *x, int n)
{
int i;
cout << "\nThe sequence after bubble sorting is;\n " << endl;
for (i = 0; i < n; i++)
printf("%c", *(x + i));
cout << "\n" << endl;
}
s
个中心酸。