1、函数模板
思考:如果重载的函数,其解决问题的逻辑是一致的、函数体语句相同,只是处理的数据类型不同,那么写多个相同的函数体,是重复劳动,而且还可能因为代码的冗余造成不一致性。
解决:使用模板
例:求绝对值函数的模板
主函数如下
int main()
{
int n=-5;
double d=-5.5;
cout<<abs(n)<<endl;
cout<<abs(d)<<endl;
return 0;
}
#include <iostream>
using namespace std;
template<typename T>
T abs(T x) {
return x < 0? -x : x;
}
int main() {
int n = -5;
double d = -5.5;
cout << abs(n) << endl; // 调用 abs<int>
cout << abs(d) << endl; // 调用 abs<double>
return 0;
}
2、排序函数模板
Description:
已知主函数如程序后缀代码所示,请为其编写适当的模板函数,使主函数的bubbleSort函数可以对一个整型数组和一个浮点数数组进行输入、排序、输出操作。
Sample Input:
无
Sample Output:
#include <iostream>
#include <iomanip>
using namespace std;
// 模板函数声明
template <typename T>
void bubbleSort(T arr[], int size);
//StudybarCommentBegin
int main()
{
const int arraySize = 10; // size of array
int a[ arraySize ] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }, i;
// display int array in original order
cout << "Integer data items in original order\n";
for ( i = 0; i < arraySize; ++i )
cout << setw( 6 ) << a[ i ];
bubbleSort( a, arraySize ); // sort the array
// display int array in sorted order
cout << "\nInteger data items in ascending order\n";
for ( i = 0; i < arraySize; ++i )
cout << setw( 6 ) << a[ i ];
cout << "\n\n";
// initialize double array
double b[ arraySize ] = { 10.1, 9.9, 8.8, 7.7, 6.6, 5.5,
4.4, 3.3, 2.2, 1.1 };
// display double array in original order
cout << "double point data items in original order\n";
for ( i = 0; i < arraySize; ++i )
cout << setw( 6 ) << b[ i ];
bubbleSort( b, arraySize ); // sort the array
// display sorted double array
cout << "\ndouble point data items in ascending order\n";
for ( i = 0; i < arraySize; ++i )
cout << setw( 6 ) << b[ i ];
cout << endl;
return 0;
} // end main
//StudybarCommentEnd
// 模板函数实现
template <typename T>
void bubbleSort(T arr[], int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
// 交换元素
T temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
3、重载函数模板printArray
Description:
重载第七章课件10页中的printArray函数模板,代码如下:
#include
using namespace std;
// function template printArray definition
template< typename T >
void printArray( const T *arrayset, int count )
{
for ( int i = 0; i < count && arrayset[i]!=‘\0’ ; i++ )
cout << arrayset[ i ] << " ";
cout << endl;
} // end function template printArray
int main()
{
const int aCount = 5; // size of array a
const int bCount = 7; // size of array b
const int cCount = 6; // size of array c
int a[ aCount ] = { 1, 2, 3, 4, 5 };
double b[ bCount ] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
char c[ cCount ] = “HELLO”; // 6th position for null
cout << “Array a contains:” << endl;
// call integer function-template specialization
printArray( a, aCount );
cout << “Array b contains:” << endl;
// call double function-template specialization
printArray( b, bCount );
cout << “Array c contains:” << endl;
// call character function-template specialization
printArray( c, cCount );
return 0;
} // end main
重载上述函数模板,使它包含两个额外的名为 int lowSubscript (范围下限)和 int highSubscript(范围上限)的整型参数。调用这个函数会打印出数组中指定范围的元素。函数将判定lowSubscript和highSubscript是否有效,如果超出数组下标范围或highSubscript比lowSubscript小,重载的printArray函数将返回0,否则,返回打印出的元素的个数。然后修改main函数,通过三个数组a、b、c来对两个版本的printArray进行测试。
注:程序后缀代码已给出。
提示:字符’\0’是不可打印字符,因此,cout<<‘\0’; 将导致输出不确定数值。
Sample Input:
无
Sample Output:
#include <iostream>
using namespace std;
// Original function template printArray definition
template< typename T >
void printArray( const T *arrayset, int count )
{
for ( int i = 0; i < count && arrayset[i]!='\0'; i++ )
cout << arrayset[ i ] << " ";
cout << endl;
} // end function template printArray
// Overloaded function template printArray with range parameters
template< typename T >
int printArray( const T *arrayset, int count, int lowSubscript, int highSubscript )
{
// Check for invalid subscripts
if (lowSubscript < 0 || highSubscript >= count || lowSubscript > highSubscript) {
return 0;
}
int elementsPrinted = 0;
for (int i = lowSubscript; i <= highSubscript; i++) {
// For char arrays, don't print null terminators
if (arrayset[i] != '\0') {
cout << arrayset[i] << " ";
elementsPrinted++;
}
}
cout << endl;
return elementsPrinted;
} // end overloaded function template printArray
//StudybarCommentBegin
int main()
{
// sizes of arrays
const int aCount = 5;
const int bCount = 7;
const int cCount = 6;
// declare and initialize arrays
int a[ aCount ] = { 1, 2, 3, 4, 5 };
double b[ bCount ] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
char c[ cCount ] = "HELLO"; // 6th position for null
int elements;
// display array a using original printArray function
cout << "\nUsing original printArray function\n";
printArray( a, aCount );
// display array a using new printArray function
cout << "\nArray a contains:\n";
elements = printArray( a, aCount, 0, aCount - 1 );
cout << elements << " elements were output\n";
// display elements 1-3 of array a
cout << "Array a from 1 to 3 is:\n";
elements = printArray( a, aCount, 1, 3 );
cout << elements << " elements were output\n";
// try to print an invalid element
cout << "Array a output with invalid subscripts:\n";
elements = printArray( a, aCount, -1, 10 );
cout << elements << " elements were output\n\n";
// display array b using original printArray function
cout << "\nUsing original printArray function\n";
printArray( a, aCount );
// display array b using new printArray function
cout << "Array b contains:\n";
elements = printArray( b, bCount, 0, bCount - 1 );
cout << elements << " elements were output\n";
// display elements 1-3 of array b
cout << "Array b from 1 to 3 is:\n";
elements = printArray( b, bCount, 1, 3 );
cout << elements << " elements were output\n";
// try to print an invalid element
cout << "Array b output with invalid subscripts:\n";
elements = printArray( b, bCount, -1, 10 );
cout << elements << " elements were output\n\n";
// display array c using original printArray function
cout << "\nUsing original printArray function\n";
printArray( a, aCount );
// display array c using new printArray function
cout << "Array c contains:\n";
elements = printArray( c, cCount, 0, cCount - 1 );
cout << elements << " elements were output\n";
// display elements 1-3 of array c
cout << "Array c from 1 to 3 is:\n";
elements = printArray( c, cCount, 1, 3 );
cout << elements << " elements were output\n";
// try to display an invalid element
cout << "Array c output with invalid subscripts:\n";
elements = printArray( c, cCount, -1, 10 );
cout << elements << " elements were output" << endl;
return 0;
} // end main
//StudybarCommentEnd
4、类模板
类模板的作用
使用类模板使用户可以为类声明一种模式,使得类中的某些数据成员、某些成员函数的参数、某些成员函数的返回值,能取任意类型(包括基本类型的和用户自定义类型)。
类模板的声明
类模板 template <模板参数表> class 类名 {类成员声明};
如果需要在类模板以外定义其成员函数,则要采用以下的形式: template <模板参数表> 类型名 类名<模板参数标识符列表>::函数名(参数表)
例9-2 类模板示例
#include <iostream>
#include <cstdlib>
using namespace std;
struct Student {
int id; //学号
float gpa; //平均分
};
template <class T>
class Store {//类模板:实现对任意类型数据进行存取
private:
T item; // item用于存放任意类型的数据
bool haveValue; // haveValue标记item是否已被存入内容
public:
Store();
T &getElem(); //提取数据函数
void putElem(const T &x); //存入数据函数
};
template <class T>
Store<T>::Store(): haveValue(false) { }
template <class T>
T &Store<T>::getElem() {
//如试图提取未初始化的数据,则终止程序
if (!haveValue) {
cout << "No item present!" << endl;
exit(1); //使程序完全退出,返回到操作系统。
}
return item; // 返回item中存放的数据
}
template <class T>
void Store<T>::putElem(const T &x) {
// 将haveValue 置为true,表示item中已存入数值
haveValue = true;
item = x; // 将x值存入item
}
int main() {
Store<int> s1, s2;
s1.putElem(3);
s2.putElem(-7);
cout << s1.getElem() << " " << s2.getElem() << endl;
Student g = { 1000, 23 };
Store<Student> s3;
s3.putElem(g);
cout << "The student id is " << s3.getElem().id << endl;
Store<double> d;
cout << "Retrieving object D... ";
cout << d.getElem() << endl;
//d未初始化,执行函数D.getElement()时导致程序终止
return 0;
}
5、整数集合类
实现整数集合类
要求:1、类中含两个私有变量,集合中元素的个数和集合中元素组成的数组。
2、用Set函数输入,Show函数输出结果(按从小到大的顺序输出各个元素)。
3、实现运算符+的重载,表示两个集合的并集。
实现运算符&的重载,表示两个集合的交集。
实现运算符-的重载,表示两个集合的差。
提示:1、集合中不可出现重复元素。
2、空集时,输出empty。
样例1
输入
3
1 2 3
4
1 2 5 6
输出
1 2 3 5 6
1 2
3
样例2
输入
3
1 2 3
3
1 2 3
输出
1 2 3
1 2 3
empty
#include <iostream>
#include <algorithm>
using namespace std;
class Cassemblage {
private:
int num;
int elements[1000]; // Assuming a maximum size for simplicity
public:
Cassemblage() : num(0) {}
void Set(int arr[], int n) {
num = 0;
for (int i = 0; i < n; ++i) {
bool found = false;
for (int j = 0; j < num; ++j) {
if (elements[j] == arr[i]) {
found = true;
break;
}
}
if (!found) {
elements[num++] = arr[i];
}
}
sort(elements, elements + num);
}
void Show() {
if (num == 0) {
cout << "empty";
} else {
for (int i = 0; i < num; ++i) {
cout << elements[i];
if (i != num - 1) {
cout << " ";
}
}
}
}
Cassemblage operator+(const Cassemblage& other) const {
Cassemblage result;
int i = 0, j = 0;
while (i < num && j < other.num) {
if (elements[i] < other.elements[j]) {
if (result.num == 0 || result.elements[result.num - 1] != elements[i]) {
result.elements[result.num++] = elements[i];
}
++i;
} else if (elements[i] > other.elements[j]) {
if (result.num == 0 || result.elements[result.num - 1] != other.elements[j]) {
result.elements[result.num++] = other.elements[j];
}
++j;
} else {
if (result.num == 0 || result.elements[result.num - 1] != elements[i]) {
result.elements[result.num++] = elements[i];
}
++i;
++j;
}
}
while (i < num) {
if (result.num == 0 || result.elements[result.num - 1] != elements[i]) {
result.elements[result.num++] = elements[i];
}
++i;
}
while (j < other.num) {
if (result.num == 0 || result.elements[result.num - 1] != other.elements[j]) {
result.elements[result.num++] = other.elements[j];
}
++j;
}
return result;
}
Cassemblage operator&(const Cassemblage& other) const {
Cassemblage result;
int i = 0, j = 0;
while (i < num && j < other.num) {
if (elements[i] < other.elements[j]) {
++i;
} else if (elements[i] > other.elements[j]) {
++j;
} else {
if (result.num == 0 || result.elements[result.num - 1] != elements[i]) {
result.elements[result.num++] = elements[i];
}
++i;
++j;
}
}
return result;
}
Cassemblage operator-(const Cassemblage& other) const {
Cassemblage result;
int i = 0, j = 0;
while (i < num && j < other.num) {
if (elements[i] < other.elements[j]) {
if (result.num == 0 || result.elements[result.num - 1] != elements[i]) {
result.elements[result.num++] = elements[i];
}
++i;
} else if (elements[i] > other.elements[j]) {
++j;
} else {
++i;
++j;
}
}
while (i < num) {
if (result.num == 0 || result.elements[result.num - 1] != elements[i]) {
result.elements[result.num++] = elements[i];
}
++i;
}
return result;
}
};
//StudybarCommentBegin
int main(int argc, char* argv[])
{
Cassemblage z1, z2, x1, x2, x3;
int i, n1, n2, a1[1000], a2[1000];
cin >> n1;
for(i=0; i<n1; i++)
{
cin >> a1[i];
}
z1.Set(a1, n1);
cin >> n2;
for(i=0; i<n2; i++)
{
cin >> a2[i];
}
z2.Set(a2, n2);
x1=z1+z2;
x1.Show();
cout << endl;
x2=z1&z2;
x2.Show();
cout << endl;
x3=z1-z2;
x3.Show();
return 0;
}
//StudybarCommentEnd