类模板里能用选择排序的方法
时间: 2023-05-26 22:07:17 浏览: 46
是的,可以在类模板中使用选择排序算法来排序不同类型的数据。例如,假设我们有以下类模板:
```
template<typename T>
class MyClass {
public:
void selectionSort(T arr[], int n) {
int i, j, min_index;
for (i = 0; i < n-1; i++) {
min_index = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_index])
min_index = j;
swap(arr[min_index], arr[i]);
}
}
// other member functions
};
```
在这个模板中,我们定义了一个名为 `selectionSort` 的函数模板,它接受一个类型为 `T` 的数组 `arr` 和一个整数 `n`,并使用选择排序算法对数组进行排序。
然后,我们可以用 `MyClass` 模板创建不同类型的对象,并使用 `selectionSort` 函数来对它们进行排序,例如:
```
MyClass<int> int_obj;
int arr[] = {3, 2, 1, 5, 4};
int_obj.selectionSort(arr, 5);
MyClass<double> double_obj;
double arr2[] = {3.2, 1.1, 2.3, 4.5, 0.5};
double_obj.selectionSort(arr2, 5);
```
在这个例子中,我们使用 `MyClass<int>` 和 `MyClass<double>` 分别创建了 `int_obj` 和 `double_obj` 两个不同类型的对象,并调用了它们的 `selectionSort` 函数来对不同类型的数组进行排序。