【C++初学】课后作业汇总复习(六) 函数模板

news2025/4/16 6:10:19

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2334921.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【第16届蓝桥杯C++C组】--- 数位倍数

Hello呀&#xff0c;小伙伴们&#xff0c;第16届蓝桥杯也完美结束了&#xff0c;无论大家考的如何&#xff0c;都要放平心态&#xff0c;今年我刚上大一&#xff0c;也第一次参加蓝桥杯&#xff0c;刷的算法题也只有200来道&#xff0c;但是还是考的不咋滴&#xff0c;但是拿不…

Numpy和OpenCV库匹配查询,安装OpenCV ABI错误

文章目录 地址opencv-python&#xff1a;4.x版本的对应numpyopencv-python&#xff1a;5.x版本的对应numpy方法2 ps&#xff1a;装个opencv遇到ABI错误无语了&#xff0c;翻了官网&#xff0c;github文档啥都没&#xff0c;记录下 地址 opencv-python&#xff1a;4.x版本的对应…

ubuntu18.04安装miniforge3

1.下载安装文件 略&#xff08;注&#xff1a;从同事哪里拖来的安装包&#xff09; 2.修改安装文件权限 chmod x Miniforge3-Linux-x86_64.sh 3.将它安装到指定位置 micromamba activate /home/xxx/fxp/fromDukto/miniforge3 4.激活 /home/xxx/fxp/fromDukto/miniforge3…

智能手机功耗测试

随着智能手机发展,用户体验对手机的续航功耗要求越来越高。需要对手机进行功耗测试及分解优化,将手机的性能与功耗平衡。低功耗技术推动了手机的用户体验。手机功耗测试可以采用powermonitor或者NI仪表在功耗版上进行测试与优化。作为一个多功能的智能终端,手机的功耗组成极…

使用U盘安装 ubuntu 系统

1. 准备U 盘制作镜像 1.1 下载 ubuntu iso https://ubuntu.com/download/ 这里有多个版本以供下载&#xff0c;本文选择桌面版。 1.2 下载rufus https://rufus.ie/downloads/ 1.3 以管理员身份运行 rufus 设备选择你用来制作启动项的U盘&#xff0c;不能选错了&#xff1b;点…

oracle 并行度(Parallel Degree)

在Oracle数据库中&#xff0c;并行度&#xff08;Parallel Degree&#xff09; 是用于控制并行处理任务的关键配置&#xff0c;旨在通过多进程协作加速大规模数据处 一、并行度的核心概念 并行度&#xff08;DOP, Degree of Parallelism&#xff09; 表示一个操作同时使用的并…

Redis-场景缓存+秒杀+管道+消息队列

缓存一致性 1.两次更新 先更新数据库&#xff0c;再更新缓存&#xff1b;先更新缓存&#xff0c;再更新数据库&#xff1b; 出现不一致问题场景&#xff1a; 先更新数据库&#xff0c;再更新缓存&#xff1b; 先更新缓存&#xff0c;再更新数据库&#xff1b; 两次更新的适…

系统的安全及应用

仓库做了哪些优化 仓库源换成国内源不使用root用户登录将不必要的开机启动项关闭内核的调优 系统做了哪些安全加固 禁止使用root禁止使用弱命令将常见的 远程连接端口换掉 系统安全及应用 Cpu负载高 java程序 运行异常中病毒&#xff1f; ps aux - - sort %cpu %mem Cpu …

PostgreSQL内幕探索—基础知识

PostgreSQL内幕探索—基础知识 PostgreSQL&#xff08;以下简称PG&#xff09; 起源于 1986 年加州大学伯克利分校的 ‌POSTGRES 项目‌&#xff0c;最初以对象关系模型为核心&#xff0c;支持高级数据类型和复杂查询功能‌。 1996 年更名为 PostgreSQL 并开源&#xff0c;逐…

WPS复制粘贴错误 ,文件未找到 mathpage.wll

文章目录 1.错误提示图片2.解决方案1.找到MathType.wll文件和MathType Commands 2016.dotm文件并复制2.找到wps安装地址并拷贝上述两个文件到指定目录 3.重启WPS 1.错误提示图片 2.解决方案 1.找到MathType.wll文件和MathType Commands 2016.dotm文件并复制 MathType.wll地址如…

驱动开发硬核特训 · Day 6 : 深入解析设备模型的数据流与匹配机制 —— 以 i.MX8M 与树莓派为例的实战对比

&#x1f50d; B站相应的视屏教程&#xff1a; &#x1f4cc; 内核&#xff1a;博文视频 - 从静态绑定驱动模型到现代设备模型 主题&#xff1a;深入解析设备模型的数据流与匹配机制 —— 以 i.MX8M 与树莓派为例的实战对比 在上一节中&#xff0c;我们从驱动框架的历史演进出…

【UE5 C++课程系列笔记】35——HTTP基础——HTTP客户端异步请求API接口并解析响应的JSON

目录 前言 步骤 一、 搭建异步蓝图节点框架 二、异步蓝图节点嵌入到引擎的执行流程 三、获取本地时间并异步返回 四、获取网络时间并异步返回 五、源码 前言 本文以请求网络/本地时间API为例&#xff0c;介绍如何实现HTTP异步请求。 步骤 一、 搭建异步蓝图节点框架 …

手机静态ip地址怎么获取?方法与解析‌

而在某些特定情境下&#xff0c;我们可能需要为手机设置一个静态IP地址。本文将详细介绍手机静态IP地址详解及获取方法 一、什么是静态IP地址&#xff1f; 静态IP&#xff1a;由用户手动设置的固定IP地址&#xff0c;不会因网络重启或设备重连而改变。 动态IP&#xff1a;由路…

Python 基础语法汇总

Python 语法 │ ├── 基本结构 │ ├── 语句&#xff08;Statements&#xff09; │ │ ├── 表达式语句&#xff08;如赋值、算术运算&#xff09; │ │ ├── 控制流语句&#xff08;if, for, while&#xff09; │ │ ├── 定义语句&#xff08;def…

Linux上位机开发实践(OpenCV算法硬件加速)

【 声明&#xff1a;版权所有&#xff0c;欢迎转载&#xff0c;请勿用于商业用途。 联系信箱&#xff1a;feixiaoxing 163.com】 图像处理里面&#xff0c;opencv基本是一个标准模块。但是由于图像处理的特点&#xff0c;如果所有的算法都是cpu来做的话&#xff0c;效率会很低。…

Spring Boot MongoDB自定义连接池配置

手打不易&#xff0c;如果转摘&#xff0c;请注明出处&#xff01; 注明原文&#xff1a;http://zhangxiaofan.blog.csdn.net/article/details/144341407 一、引言 在 Spring Boot 应用中使用 MongoDB 时&#xff0c;合理配置连接池可以显著提升数据库访问的性能和稳定性。默…

游戏引擎学习第223天

回顾 今天我们正在进行过场动画序列的制作&#xff0c;因此我想深入探讨这个部分。昨天&#xff0c;我们暂时停止了过场动画的制作&#xff0c;距离最终结局还有一些内容没有完成。今天的目标是继续完成这些内容。 我们已经制作了一个过场动画的系列&#xff0c;并把它们集中…

DeepSeek 助力 Vue3 开发:打造丝滑的日历(Calendar),日历_基础功能示例(CalendarView01_01)

前言:哈喽,大家好,今天给大家分享一篇文章!并提供具体代码帮助大家深入理解,彻底掌握!创作不易,如果能帮助到大家或者给大家一些灵感和启发,欢迎收藏+关注哦 💕 目录 DeepSeek 助力 Vue3 开发:打造丝滑的日历(Calendar),日历_基础功能示例(CalendarView01_01)📚…

LabVIEW配电器自动测试系统

随着航天技术的迅猛发展&#xff0c;航天器供配电系统的结构越来越复杂&#xff0c;对配电器的功能完整性、稳定性和可靠性提出了更高要求。传统人工测试方式难以满足高效率、高精度、可重复的测试需求。本项目开发了一套基于LabVIEW平台的宇航配电器自动测试系统&#xff0c;融…

PhotoShop学习09

1.弯曲钢笔工具 PhotoShop提供了弯曲钢笔工具可以直观地创建路径&#xff0c;只需要对分段推拉就能够进行修改。弯曲港币工具位于工具面板中的钢笔工具里&#xff0c;它的快捷键为P。 在使用前&#xff0c;可以把填充和描边选为空颜色&#xff0c;并打开路径选项&#xff0c;勾…