为什么在实现选择排序时更喜欢使用函数模板而不是将int数组传递给函数? 如果我们只是想比较整数,为什么我们希望它可以在任何类型的数组上运行? 为什么我们在交换函数中使用不同的类型?我们不能再次使用Item了吗?
template <class Item>
void selectionSort(Item a[], int n) {
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (a[j] < a[min])
min = j;
swap(a[i], a[min]);
}
}
}
template <class Object>
void swap(Object &el1, Object &el2) {
Object temp = el1;
el1 = el2;
el2 = temp;
}
答案 0 :(得分:1)
为什么在实现选择排序时优先使用函数模板而不是将int数组传递给函数?
然后,您可以使用该函数对任何支持以下操作的对象类型的数组进行排序:
operator<
)。根据我的经验,创建功能模板通常可以改进设计。它迫使你根据以下方面来考虑这个功能:
它使您的思维清晰明了,从而改进了设计。