【发布时间】:2021-08-15 03:40:41
【问题描述】:
我正在使用模板函数,并希望创建一个同时对整数和字符串进行排序的函数。我已经设法让它与整数一起工作,但在字符串方面遇到了麻烦。
这是我目前的代码。
#include <iostream>
#include <string>
using namespace std;
template <class T>
void print(T arr[], int n);
template <class T>
void swap(T arr[], int i, int j);
template <class T>
T getSmallest(T arr[], int start, int end);
template <class T>
void selectionSort(T arr[], int n);
int main()
{
int n = 10;
int iarr[] = { 3,5,9,2,1,7,8,4,0,6 };
selectionSort<int>(iarr, n);
print<int>(iarr, n);
cout << endl;
string sarr[] = { "skunk", "hedgehog", "aardvark", "zebra", "rat", "cat", "hippopotamus", "hamster", "manatee", "red panda" };
selectionSort<string>(sarr, n);
print<string>(sarr, n);
cout << endl;
return 0;
}
// PRE: length of arr = n
// PARAM: arr = array of integers of length n
// POST: prints arr[0:n]
template <class T>
void print(T arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << endl;
}
}
// PRE: i, j < length of arr
// PARAM: arr = array of integers of length n, i and j are indexes
// POST: swaps arr[i] with arr[j]
template <class T>
void swap(T arr[], int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// PRE: 0 <= start < end <= length of arr
// PARAM: arr = array of integers
// start = start index of sub-array
// end = end index of sub-array + 1
// POST: returns index of smallest value in arr{start:end}
template <class T>
T getSmallest(T arr[], int start, int end) {
T smallest = start;
for (int i = start + 1; i < end; ++i) {
if (arr[i] < arr[smallest]) {
smallest = i;
}
}
return smallest;
}
// PRE: length of arr = n
// PARAM: arr = array of integers of length n
// POST: sorts arr in ascending order
template <class T>
void selectionSort(T arr[], int n) {
for (int i = 0; i < n - 1; ++i) {
int smallest = getSmallest(arr, i, n);
swap(arr, i, smallest);
}
}
我知道我需要找到某种方法让“最小”能够以某种方式适用于字符串。但简单地将它从 int 转换为模板 T 是行不通的。有什么建议吗?
【问题讨论】:
-
“不工作”是什么意思?你得到一个编译器错误吗?
-
@stackoverflow.com/users/4117728/463035818-is-not-a-number 我从编译器中得到以下一些错误“ main.cpp: In instantiation of 'void selectionSort(T*, int) [with T = std::__cxx11:: basic_string
]': main.cpp:27:31: 从这里需要 main.cpp:82:7: 错误:在初始化 int 最小时无法将 'std::__cxx11::basic_string ' 转换为 'int' = getSmallest(arr, i, n); ^~~~~~~~" -
请编辑问题以包含编译器输出,然后删除评论。
标签: c++ string sorting templates