llmstory
Generics and Templates: Code Refactoring and Benefits
1.

Explain the core concept of 'generics' (or 'templates' in C++) in programming. Describe why this feature is powerful and what common problems it aims to solve in software development. (20 points)

Code Review Scenario

You are reviewing a colleague's code and notice significant duplication. Specifically, they have implemented two functions, sortIntArray and sortStringArray, which implement the exact same bubble sort algorithm but operate on different data types.

Below are the original duplicated functions:

1#include <vector> 2#include <string> 3#include <algorithm> // For std::swap 4#include <iostream> 5 6void sortIntArray(std::vector<int>& arr) { 7 int n = arr.size(); 8 for (int i = 0; i < n - 1; ++i) { 9 for (int j = 0; j < n - i - 1; ++j) { 10 if (arr[j] > arr[j + 1]) { 11 std::swap(arr[j], arr[j + 1]); 12 } 13 } 14 } 15} 16 17void sortStringArray(std::vector<std::string>& arr) { 18 int n = arr.size(); 19 for (int i = 0; i < n - 1; ++i) { 20 for (int j = 0; j < n - i - 1; ++j) { 21 if (arr[j] > arr[j + 1]) { // String comparison works naturally 22 std::swap(arr[j], arr[j + 1]); 23 } 24 } 25 } 26}
2.

Refactor the provided duplicated C++ code into a single, generic function using C++ templates that can sort a std::vector of any comparable data type. (25 points)

3.

Demonstrate how to use your new generic sorting function with both an std::vector<int> and an std::vector<std::string>, showing successful usage and printing the sorted vectors. (25 points)

4.

Discuss the primary benefits of using generics/templates, specifically focusing on 'type safety' and 'code reuse'. Provide concrete examples within the context of your refactored sorting function to illustrate these benefits clearly. (30 points)

Copyright © 2025 llmstory.comPrivacy PolicyTerms of Service