C++ 基础练习 - Chapter 12 (基础练习 完结版)

news2024/11/24 13:06:21

Review Questions

12.1 What is generic Programming? How is it implemented in C++?

Answer:

Generic programming is an approach where generic types are used as parameters in algorithms so that they work for variety of suitable data types and data structures.

It is implemented in C++ using class templates.

12.2 A template can be considered as a kind of macro. Then what is the difference between them?

Answer:

Templates are a feature of the C++ programming language at allows a functions or class to work on many different data types without being written for each one. Templates are of great utility programmers in C++, especially when combined with multiple inheritance and operator overloading. The C++ STL provides many usefu functions within a framework of connected templates.

On the other hand the # define directive is typically used to associate meaningful identifiers with constants, keywords and commonly used statements or expressions. Identifiers that represent constants are sometimes called “symbolic constant” or “manifest constant”.

Identifiers that represents statements or expressions are called “macro”. In this preprocessor documentation only the term “macro” is used.

12.3 Distinguish between overloaded functions and junction templates.

Answer:

Basic difference is function body will not differ in function overloading.

12.4 Distinguish between the terms class template and template class.

Answer:

Class template is a generic class. The class template definition is very similar to an ordinary class definition except the prefix template and the use of type T.

On the other hand a class created from a class template is called a template class. The process of creating a specific class from a class template is called instantiation.

12.5 A class (or function) template is known as a parameterized class (or function). Comment.

Answer:

When an object of specific type is defined for actual use, the template definition for that class is substituted with the required data type. Since a template is defined with a parameter that would be replaced by a specified data type at the time of actual use of the class or function, the templates are called parameterized classes or functions.

12.6 What is an exception?

Answer:

Exceptions are run-time anomalies or unusual conditions that a program may encounter while executing.

12.7 How is an exception handled in C++?

Answer:

C++ exception handling mechanism is basically built upon the three keywords, namely, try, throw and catch. The keyword try is used to preface a block of statements which may generate exceptions. This block is known as try block. When an exception is detected, it is thrown using throw statement in the try block. A catch block defined by the keyword “catch” catches the exception thrown statement in the try block and handles it appropriately. This relationship is shown below:

在这里插入图片描述

12.8 What are the advantages of using exception handling mechanism in a program?

Answer:

We often come across some peculiar problems other than logic or syntax errors. These error occurs at run time and the whole program may be crashed. To avoid these types of errors we use exception handling mechanism in a program.

12.9 When should a program thrown an exception?

Answer:

When an exception is detected in try block then a program should throw an exception to catch block.

12.10 When is a catch(…) handler is used?

Amswer:

To catch all exceptions catch(…) handler is used.

12.11 What is an exception specification?When is it used?

Answer:

Exception specification is a way to restrict a function to throw only certain specified exceptions. The general form of using an exception specification is:

type function (argument list) throw (type-list)
{
	function body
}

12.12 What should be placed inside a “try” block?

Answer:

A throw statement should be placed inside a try block.

12.13 What should be placed inside a “catch” block?

Answer:

A appropriate message for which an exception is caught shoud be placed in catch block.

12.14 When do we use multiple “catch” handlers?

Answer:

When there are more than one exception in a program, then we use multiple catch statements.

Programming Exercises

12.1 Write a function template for finding the minimum value contained in an array.

#include <iostream>
using namespace std;

const int size = 5;

template <class T>
class vector
{
    T v[size];
public:
    vector(){}
    vector(T *b);
    void show();
    T minimum(vector<T> &m);
};

template <class T>
vector<T>::vector(T *b)
{
    for(int i=0;i<size;i++)
        v[i] = b[i];
}

template<class T>
T vector<T>::minimum(vector<T> &m)
{
    int j = 0;
    for(int k=1;k<size;k++)
    {
        if(m.v[j]>m.v[k])
            j = k;
    }
    return m.v[j];
}

template<class T>
void vector<T>::show()
{
    cout << "(";
    for(int t=1;t<size;t++)
        cout << ", " << v[t];
    cout << " )" << endl;
}

int main()
{
    int x[size] = {5, 7, 3, 1, 8};
    float y[size] = {1.2, 1.5, 3.1, 1.1, 0.501};
    vector<int> v1;
    vector<float> v2;
    v1 = x;
    v2 = y;

    cout << "Minimum value = " << v1.minimum(v1) << " of array";
    v1.show();

    cout << "Minimum value = " << v2.minimum(v2) << " of array";
    v2.show();

    return 0;
}

12.2 Write a program containing a possible exception. Use a try block to throw it and a catch block to handle it promptly.

#include <iostream>
#include <cmath>
#define PI 3.1416
using namespace std;

void power_factor(float a)
{
    if(a>1 || a<-1)
        throw(a);
    else
        cout << "Voltage(V) is lagging from current(I) by : "<< acos(a)*180/PI << "degree\n";
}

int main()
{
    float a;
    try
    {
        cout << "Enter power factor ";
        cin >> a;
        power_factor(a);
    }
    catch(float b)
    {
        cout << "Caught an exception \n";
    }
    return 0;
}

12.3 Wrtie a program that demonstrates how certain exception types are not allowed to be thrown.

#include <iostream>
using namespace std;

void empty() throw()
{
    cout << "In empty()\n";
}

void with_type(float x) throw(int)
{
    if(x==1)
        throw (1);
    else if (x==1.1)
        throw(2.1);
}

int main()
{
    try
    {
        empty();
        with_type(1);
    }
    catch(int n)
    {
        cout<< "Caught an int = " << n;
    }
    catch(float)
    {
        cout<<"Caught a float ";
    }

    return 0;
}

12.4 Write a program to demonstrate the concept of re-throwing an exception.

#include <iostream>
using namespace std;

void division(int a, int b)
{
    try
    {
        if(b==0)
            throw b;
        else
            cout << " a/b = " << (float)a/b << endl;
    }
    catch(int)
    {
        cout << "Caught an exception as first throwing \n";
        throw;
    }
}

int main()
{
    int a, b;
    cout << "Enter the value of a & b : ";
    cin >> a >> b;
    try
    {
        division(a, b);
    }
    catch(int)
    {
        cout << "Caught an exception as re-throwing \n";
    }

    return 0;

12.5 Write a main program that calls a deeply nested function containing an exception. Incorporate necessary exception handling mechanism.

#include <iostream>
using namespace std;
long int square(int i)
{
    return i*i;
}

long int sum(int n)
{
    long int s;
    s = 0;
    for(int i=1;i<=n;i++)
    {
        s+=square(i);
    }

    return s;
}

void display(int m)
{
    try
    {
        if(m<0)
            throw m;
        else
            cout << sum(m)<<endl;
    }
    catch(int n)
    {
        cout<<"Caught an exception \n";
    }
}

int main()
{
    int n;
    cout << "Enter a positive number ";
    cin>>n;
    display(n);
    return 0;
}

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

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

相关文章

【Spring】通过Aspects实现面向切面编程(AOP)

目录 1.概念理解 2. 案例说明 1.概念理解 【注】一些概念来自&#xff1a;https://blog.csdn.net/Kaiser__/article/details/135894150 横切关注点 分散在每个各个模块中解决同一样的问题&#xff0c;如用户验证、日志管理、事务处理、数据缓存都属于横切关注点。这个概念不是…

【C++刷题】优选算法——贪心第一辑

什么是贪心算法 贪心策略&#xff1a;局部最优 -> 全局最优 “贪婪鼠目寸光” 1、把解决问题的过程分为若干步 2、解决每一步的时候&#xff0c;都选择当前看起来“最优的”解法 3、“希望”得到全局最优解 贪心算法的特点 贪心策略的提出是没有标准或者模板的 正确的贪心策…

项目小结(中)

一.文件分片上传 在文件上传的逻辑中&#xff0c;文件以MD5唯一&#xff0c;然后记录已经储存的文件md5&#xff0c;如果已上传&#xff0c;就秒传&#xff0c;并记录班级上传文件信息。 如果请求文件上传时&#xff0c;发现班级已经上传了一部分&#xff0c;这里就会把班级上…

秋招复习笔记——八股文部分:网络IP

终于来到了网络的最后一篇&#xff0c;继续加油&#xff01; IP 知识全家桶 IP 基本认识 IP 在 TCP/IP 参考模型中处于第三层&#xff0c;也就是网络层。 网络层的主要作用是&#xff1a;实现主机与主机之间的通信&#xff0c;也叫点对点&#xff08;end to end&#xff09…

【Vue3】Pinia修改数据

【Vue3】Pinia修改数据 背景简介开发环境开发步骤及源码总结 背景 随着年龄的增长&#xff0c;很多曾经烂熟于心的技术原理已被岁月摩擦得愈发模糊起来&#xff0c;技术出身的人总是很难放下一些执念&#xff0c;遂将这些知识整理成文&#xff0c;以纪念曾经努力学习奋斗的日子…

锐捷RCNA | 远程登录与路由技术

锐捷RCNA | 远程登录与路由技术 一、远程登录配置1. Telnet远程登录介绍2. 案例1--设置远程登录密码实现远程登录3. 案例2--定义不同用户账户实现远程用户权限隔离4. SSH远程登录介绍5. 案例--通过SSH功能远程管理设备 二、路由技术1. 直连路由的数据通信2. 间接路由的数据通信…

标准IO

fprintf和fscanf fprintf int printf(const char *format, ...); 把数据输出到终端 int fprintf(FILE *stream, const char *format, ...); 功能&#xff1a; 将format字符串中的内容&#xff0c;输出到stream文件流指针指向的文件中去&#xff0c;想要将数据以何种形式输…

基于XxlCrawler的Java执行JS渲染方式实战-以获取商飞C919飞行照片为例

目录 前言 一、抓取目标解析 1、原始网站介绍 2、列表页面结构解析 二、XxlCrawler的常规配置 1、PageVo对象的定义 2、定义XxlCrawler并启动 三、使用HtmlUnit来执行动态渲染 1、在pom.xml中加入htmlunit的引用 2、设置PageLoader加载器 3、执行抓取 四、总结 前言…

看,esp8266就是这么简单

材料准备 1.esp 8266 2.一条可以传输数据的数据线 3一台电脑 前言 如今是物联网的时代&#xff0c;例如“智能家居&#xff0c;无人驾驶……”&#xff0c;多方面的进行物联网改革与创新。那其中&#xff0c;物联网主要的是联网。那通常都是以“esp 8266”和“esp 32”占据了…

在Kylin服务器安装PostgreSQL16数据库

1、下载PostgreSQL16安装包 下载地址https://www.postgresql.org/ftp/source/v16.3/ 2、安装依赖和ICU库 查看服务器版本 yum install -y perl-ExtUtils-Embed readline-devel zlib-devel pam-devel libxml2-devel libxslt-devel openldap-devel python-devel gcc-c opens…

在抖音做电商推广,货架场非做不可

前一段时间跟几个做电商的朋友聊天&#xff0c;我发现大家的干劲儿还挺满的&#xff0c;讨论的话题也出奇地一致&#xff1a;要找新增量。 其中有个朋友是做服装品类的&#xff0c;做得还不错。我请教他秘诀&#xff0c;他说&#xff1a;做电商&#xff0c;推广拿量非常关键。…

MySQL笔记(七):索引

一、索引优化速度 创建对应字段的索引&#xff0c;只对该列有效&#xff0c;只能提高该列的查询速度 创建索引后&#xff0c;查询速度变快&#xff0c;但是表占用空间变大 create index 索引名 on 表名(需要创建索引的列)二、索引的原理 普通索引允许该字段重复 全文索引&#…

Resize Observer监测DOM元素尺寸改变的神器

前言 大家在遇到需要监测DOM元素尺寸大小的需求时&#xff0c;可能第一时间想到的都是使用window.addEventListener来监听resize 事件&#xff0c; 但是reize事件会在一秒内触发将近60次&#xff0c;所以很容易在改变窗口大小时导致性能问题。因为它会监听我们页面每个元素的…

MySQL总体功能

基于Innodb存储引擎的讨论 MySQL 核心功能 功能解决的问题ACID模型数据并发访问&#xff0c;和奔溃恢复安全问题,一致性&奔溃恢复索引数据查询效率问题备份容错设计,解决硬件错误带来的问题复制数据迁移监控执行数据库操作的异常记录

《嵌入式 - 嵌入式大杂烩》ARM Cortex-M寄存器详解

1 ARM Cortex-M寄存器概述 ARM Cortex-M提供了 16 个 32 位的通用寄存器(R0 - R15),如下图所示。前15个(R0 - R14)可以用作通用的数据存储,R15 是程序计数器 PC,用来保存将要执行的指令。除了通用寄存器,还有一些特殊功能寄存器。特殊功能寄存器有预定义的功能,而且必须通…

Java编码算法

编码 1.编码算法2.URL编码**URLEncoder类&#xff0c;主要进行编码****URLDecoder类&#xff0c;主要进行解码** 3.Base64编码Base64编码Base64的补充字符Base64的占位符Base64的应用 结论&#xff1a; 1.编码算法 什么是编码? ASCII码就是一种编码&#xff0c;字母A的编码是…

C语言典型例题28

《C程序设计教程&#xff08;第四版&#xff09;——谭浩强》 习题2.5 输入一个华氏温度&#xff0c;要求输出摄氏温度。公式为C5/9(F-32)&#xff0c;要求输出要有文字说明&#xff0c;取两位小数 数学知识&#xff1a; &#xff08;1&#xff09;华氏温度与摄氏温度&#x…

MySQL(六):mysql 约束

基本介绍&#xff1a;约束用于确保数据库的数据满足特定的商业规则&#xff0c;约束包括&#xff1a;not null、unique、primary key、foreign key 、check五种。 一、主键的使用&#xff08;primary key) 字段名 字段类型 primary key用于唯一的表示表行的数据&#xff0c;当…

SpringBoot基础 第二天

SpringBoot对静态资源的映射: (1) 要在src/main/resources文件夹下创建static和templates两个文件夹staitc存储静态资源,templates存储模板引擎 (2)要在pom.xml依赖下导入依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>…

VS项目打包成lib库并使用

一、新建一个静态库项目 一般要把项目设为Release模式 二、添加文件 将所需要打包的头文件、源文件添加到该静态库项目中 三、生成项目 生成成功后即可在Release文件夹出现找到相应的.lib文件 四、使用静态库 将静态库文件复制到项目文件夹中&#xff0c;然后在项目属性设…