功能:给定一个string的字符数组(左图),返回一个已经排序好的string的字符数组(右图)。
c++实现如下:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
void sort_string(string *in_array, int n, string *out_array)
{
vector<string> strArray;
int i,j = 0;
for (int i = 0; i < n; i++)
{
strArray.push_back(in_array[i]);
}
sort(strArray.begin(), strArray.end());
vector<string>::iterator st;
for (st = strArray.begin(); st != strArray.end(); st++)
{
//cout << *st << endl;//打印结果
out_array[j++] = *st;
}
}
int main()
{
string str[4] = { "hello, world!", "welcome to cpp.", "effective c++", "exceptional c++" };
string str_out[4];
sort_string(str, 4, str_out);
for (int j = 0; j < 4; j++)
cout << str_out[j] << endl;
}
vs运行结果如下:
TIP:
string数组传参 数组名就可以,形参类型string *
string [5]; 不用初始化,类会调用默认析构函数初始化,char 数组却不行!!!