C++ program that uses the template keyword to create a generic function for finding the maximum value in an array. This program demonstrates how to define and use templates, along with sample output and programming comments.
#include <iostream>
// Define a template function to find the maximum value in an array of any data type.
template <typename T>
T findMax(const T arr[], int size) {
T maxVal = arr[0]; // Assume the first element is the maximum.
// Iterate through the array to find the maximum value.
for (int i = 1; i < size; ++i) {
if (arr[i] > maxVal) {
maxVal = arr[i]; // Update maxVal if a larger element is found.
}
}
return maxVal;
}
int main() {
// Test the findMax function with different data types.
int intArray[] = {12, 45, 6, 78, 23};
double doubleArray[] = {3.14, 2.718, 1.618, 0.577};
char charArray[] = "template";
// Find the maximum values for each array.
int maxInt = findMax(intArray, 5);
double maxDouble = findMax(doubleArray, 4);
char maxChar = findMax(charArray, 7);
// Display the results.
std::cout << "Maximum integer value: " << maxInt << std::endl;
std::cout << "Maximum double value: " << maxDouble << std::endl;
std::cout << "Maximum character value: " << maxChar << std::endl;
return 0;
}
Maximum integer value: 78
Maximum double value: 3.14
Maximum character value: t
In C++, you can create template classes, which are classes that are parameterized by one or more types. Template classes allow you to create generic data structures or algorithms that work with different data types. Here's an example of how to define and use a template class in C++ with sample code and comments:
#include <iostream>
// Define a template class for a generic Pair of values
template <typename T1, typename T2>
class Pair {
public:
Pair(const T1& first, const T2& second) : first(first), second(second) {}
void Display() const {
std::cout << "First: " << first << ", Second: " << second << std::endl;
}
private:
T1 first;
T2 second;
};
int main() {
// Create instances of the Pair class with different data types
Pair<int, double> pair1(42, 3.14);
Pair pair2("Hello", 'C');
// Display the values in the pairs
pair1.Display();
pair2.Display();
return 0;
}
First: 42, Second: 3.14
First: Hello, Second: C
question
question2