Write the Insertion Sort as a function that takes an argument of a ”vector<string> reference“ representing an unsorted list of strings to turn it into a list of strings in an alphabetical order . Test the function with a main function . 用c++,並且要用using namespace std;
时间: 2024-02-19 07:59:09 浏览: 21
好的,以下是Insertion Sort的函数实现:
```c++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void insertionSort(vector<string> &arr) {
int n = arr.size();
for (int i = 1; i < n; ++i) {
string key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
vector<string> arr = {"apple", "orange", "banana", "pear", "kiwi"};
insertionSort(arr);
for (string s : arr) {
cout << s << " ";
}
cout << endl;
return 0;
}
```
使用vector<string>引用作为参数传递,可以直接在函数内部修改原始的vector。main函数里面我们可以调用insertionSort函数,并将排序后的结果输出。