简体   繁体   中英

Using templates in selectionSort function in C++

Why it is preferred to use function templates when implementing selection sort instead of passing an int array to function? Why do we want that it can operate on arrays of any types if we are just trying to compare integers? Why did we use a different type in swap function? Couldn't we use Item again?

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;
}

Why it is preferred to use function templates when implementing selection sort instead of passing an int array to function?

Then, you can use the function to sort an array of any object type which supports the following operations:

  1. The less than comparison operator ( operator< ).
  2. The swap function.

In my experience, creating function templates usually improves the design. It forces you to think of the function in terms of:

  1. The operations that are independent of the object types.
  2. The operations that are object type-specific.

It brings clarity to your thinking, which leads to an improved design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM