C++ Primer Plus第八章课后习题总结

news/2025/2/27 8:13:47

1. 编写通常接受一个参数(字符串的地址),并打印该字符串的函数。然而,如果提供了第二个参数(int类型),且该参数不为0,则该函数打印字符串的次数将为该函数被调用的次数(注意,字符串的打印次数不等于第二个参数的值,而等于函数被调用的次数)。是的,这是一个非常可笑的函数,但它让您能够使用本章介绍的一些技术。在一个简单的程序中使用该函数,以演示该函数是如何工作的。

代码如下: 

#include <iostream> 
using namespace std;
void print(const char *, int k = 1);
int main(){
	
	print("I'm the best!");
	print("I'm the best!", 5);
	print("I'm the best!");
	print("I'm the best!");
	
	return 0;
}
void print(const char *str, int n){
	cout << str << endl;
}

输出如下:

2. CandyBar结构包含3个成员,第一个成员存储candy bar的品牌名称;第二个成员存储candy bar的重量(可能有小数);第三个成员存储candy bar的热量(整数)。请编写一个程序,它使用一个这样的函数,即将CandyBar的引用、char指针、double和int作为参数,并用最后3个值设置相应的结构成员。最后3个参数的默认值分别为“Millennium Munch”、2.85和350。另外,该程序还包含一个以CandyBar的引用为参数,并显示结构内容的函数。请尽可能使用const。 

代码如下:

#include <iostream>
#include <string>
using namespace std;

struct CandyBar{
	char *brand;
	double weight;
	int heat;
};

void getInfo(CandyBar &, char *br = "Millennium Munch", double w = 2.85, int h = 350);
void showInfo(const CandyBar &);

int main(){
	CandyBar cb;
	getInfo(cb, "MJJ", 3.55, 120);
	showInfo(cb);
	return 0;
}
void getInfo(CandyBar &cb, char *br, double w, int h){
	cb.brand = br;
	cb.weight = w;
	cb.heat = h;
}
void showInfo(const CandyBar &cb){
	cout << "The brand is:" << cb.brand << endl;
	cout << "The weight is:" << cb.weight << endl;
	cout << "The heat is:" << cb.heat << endl;
}

输出如下:

 3. 编写一个函数,它接受一个指向string对象的引用作为参数,并将该string对象的内容转化成大写,为此可以使用表6.4描述的函数toupper()。然后编写一个程序,它通过使用一个循环让您能够用不同的输入来测试这个函数,该程序的运行如下:

Enter a string (q to quit):go away
GO AWAY
Enter a string (q to quit):good grief!
GOOD GRIEF!
Enter a string (q to quit):q
Bye.

代码如下: 

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

void toupper(string &);
int main(){
	string s;
	cout << "Enter a string (q to quit):";
	while(getline(cin, s) && s != "q"){
		toupper(s);
		cout << s << endl;
		cout << "Enter a string (q to quit):";
	}
	cout << "Bye.";
	return 0;
}
void toupper(string &str){
	for(int i = 0; str[i] != '\0'; i++){
		if(islower(str[i])){
			str[i] -= 32;
            //str[i] = toupper(str[i]);
		}
		else{
			continue;
		}
	}
}

 输出如下:

 

4.下面是一个程序框架:

#include<iostream>
#include<cstring>
using namespace std;

struct stringy{
    char * str;
    int ct;
};

int main()
{
    stringy beany;
    char testing[] = "Reality isn't what it used to be.";
    set(beany, testing);
    show(beany);
    show(beany, 2);
    testing[0] = 'D';
    testing[1] = 'u';
    show(testing);
    show(testing, 3);
    show("Done!");

    return 0;
}

请提供其中描述的函数和原型,从而完成该程序。注意,应有两个show()函数,每个都使用默认参数。请尽可能使用const参数。set()使用new分配足够的空间来存储指定的字符串。这里使用的技术与设计和实现类时使用的相似。(可能还必须修改头文件的名称,删除using编译指令,这取决于所用的编译器)。

代码如下:

#include<iostream>
#include<string>
using namespace std;

struct stringy{
    char * str;
    int ct;
};

void set(string &, const char *);
void show(string , int n = 1);
void show(const char *, int n = 1);
int main()
{
    string beany;
    char testing[] = "Reality isn't what it used to be.";
    set(beany, testing);
    show(beany);
    show(beany, 2);
    testing[0] = 'D';
    testing[1] = 'u';
    show(testing);
    show(testing, 3);
    show("Done!");

    return 0;
}
void set(string &s, const char *c){
	s = c;
}
void show(string s, int n){
	for(int i = 0; i < n; i++){
		cout << s << endl;
	}
}
void show(const char *c, int n){
	while(*c != '\0'){
		cout << *c;
		c++;
	}
	cout << endl;
}

输出如下:

5.编写模板函数max5(),它将一个包含5个T类型元素的数组作为参数,并返回数组中最大的元素(由于长度固定,因此可以在循环中使用硬编码,而不必通过参数来传递)。在一个程序使用该函数,将T替换为一个包含5个int值的数组和一个包含5个double值的数组,以测试该函数。 

#include <iostream>

template <class T>
T max(T[]);

int main(){
	using namespace std;
	int arr1[5] = {1, 2, 3, 4, 5};
	double arr2[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
	int max1 = max(arr1);
	double max2 = max(arr2);
	cout << "The max number in arr1 is:" << max1 << endl;
	cout << "The max number in arr2 is:" << max2 << endl;
	return 0;
}

template <class T>
T max(T arr[]){
	T max = arr[0];
	for(int i = 1; i < 5; i++){
		if(max < arr[i]){
			max = arr[i];
		} 
	}
	return max;
}

6.编写模板函数maxn(),他将由一个T类型元素组成的数组和一个表示数组元素数目的整数作为参数,并返回数组中最大的元素。在程序对它进行测试,该程序使用一个包含6个int元素的数组和一个包含4个都不了元素的数组来调用该函数。程序还包含一个具体化,他将char指针数组和数组中的指针数量作为参数,并返回最长的字符串的地址。如果有多个这样的字符串,则返回其中第一个字符串的地址。使用由5个字符串指针组成的数组来测试该具体化。

代码如下:

#include <iostream>
#include <cstring>

template <typename T>
T maxn(T* arr, int n){
	T max = arr[0];
	for(int i = 1; i < n; i++){
		if(max < arr[i]){
			max = arr[i];
		} 
	}
	return max;
}
template <>
const char* maxn(const char* arr[5], int n){
	int max = strlen(arr[0]);
	int index = 0;
	for(int i = 1; i < n; i++){
		if(max < strlen(arr[i])){
			max = strlen(arr[i]);
			index = i;
		} 
	}
	return arr[index];
}

int main(){
	using namespace std;
	int arr1[6] = {1, 2, 3, 4, 5, 6};
	double arr2[4] = {1.1, 1.2, 2.3, 4.5};
	const char *arr3[5] = {"abc", "aabbcc", "adsafdfgd", "dsggr", "a"};
	int max1 = maxn(arr1, 6);
	double max2 = maxn(arr2, 4);
	const char* max3 = maxn(arr3, 5);
	cout << "The max in arr1:" << max1 << endl;
	cout << "The max in arr2:" << max2 << endl;
	cout << "The max in arr3:" << max3 << endl;
	return 0;
}

输出如下:

7.修改程序清单8.14,使其使用两个名为SumArray()的模板函数来返回数组元素的总和,而不是显示数组的内容。程序应显示thing的总和以及所有debt的总和。

程序清单8.14如下:

/******************程序清单8.14******************/
// tempover.cpp --- template overloading
#include <iostream>

template <typename T>            // template A
void ShowArray(T arr[], int n);

template <typename T>            // template B
void ShowArray(T * arr[], int n);

struct debts
{
    char name[50];
    double amount;
};

int main()
{
    using namespace std;
    int things[6] = {13, 31, 103, 301, 310, 130};
    struct debts mr_E[3] =
    {
        {"Ima Wolfe", 2400.0},
        {"Ura Foxe", 1300.0},
        {"Iby Stout", 1800.0}
    };
    double * pd[3]; 

// set pointers to the amount members of the structures in mr_E
    for (int i = 0; i < 3; i++)
        pd[i] = &mr_E[i].amount;

    cout << "Listing Mr. E's counts of things:\n";
// things is an array of int
    ShowArray(things, 6);  // uses template A
    cout << "Listing Mr. E's debts:\n";
// pd is an array of pointers to double
    ShowArray(pd, 3);      // uses template B (more specialized)
    // cin.get();
    return 0;
}

template <typename T>
void ShowArray(T arr[], int n)
{
    using namespace std;
    cout << "template A\n";
    for (int i = 0; i < n; i++)
        cout << arr[i] << ' ';
    cout << endl;
}

template <typename T>
void ShowArray(T * arr[], int n)
{
    using namespace std;
    cout << "template B\n";
    for (int i = 0; i < n; i++)
        cout << *arr[i] << ' ';
    cout << endl; 
}

代码如下: 

#include <iostream>

template <typename T>
T SumArray(T arr[], int n);

template <typename T>
T SumArray(T* arr[], int n);

struct debts
{
    char name[50];
    double amount;
};

int main()
{
    using namespace std;
    int things[6] = {13, 31, 103, 301, 310, 130};
    struct debts mr_E[3] =
    {
        {"Ima Wolfe", 2400.0},
        {"Ura Foxe", 1300.0},
        {"Iby Stout", 1800.0}
    };
    double * pd[3]; 

    for (int i = 0; i < 3; i++)
        pd[i] = &mr_E[i].amount;

    int sum1 = SumArray(things, 6);
	cout << "The sum of Mr. E's counts of things:" << sum1 << endl;
    double sum2 = SumArray(pd, 3);
    cout << "The sum of Mr. E's debts:" << sum2;
    return 0;
}

template <typename T>      
T SumArray(T arr[], int n){
	T sum;
	for(int i = 0; i < n; i++){
		sum += arr[i];
	}
	return sum;
}
template <typename T>         
T SumArray(T* arr[], int n){
	T sum;
	for(int i = 0; i < n; i++){
		sum += *arr[i];
	}
	return sum;
}

输出如下:


http://www.niftyadmin.cn/n/5869784.html

相关文章

JVM垃圾回收器深度底层原理分析与知识体系构建

一、垃圾回收的基本步骤 标记&#xff08;Marking&#xff09; 从GC Roots&#xff08;如虚拟机栈、方法区静态变量、本地方法栈等&#xff09;出发&#xff0c;遍历对象引用链&#xff0c;标记所有可达对象为存活对象&#xff0c;未被标记的则视为垃圾。此阶段需暂停用户线程&…

224Gb/s信号完整性测试治具设计(二)

第一篇看这里&#xff1a; 224Gb/s信号完整性测试治具设计&#xff08;一&#xff09;-CSDN博客 聚焦解决方案空间 始终满足 1.6T 测试夹具的目标插入损耗要求 IEEE P802.3dj 中当前的插入损耗规范要求&#xff0c;在 53.125 GHz 频率下&#xff0c;主机合规板&#xff08…

无人机遥控器的亮度 和 两个工作频率

工作频率 2.4000-2.4835 GHz &#xff0c; 5.725-5.850 GHz 1.这是一个无人机的遥控器的两个工作频率&#xff0c;为什么会有两个工作频率&#xff1f; 无人机的遥控器采用双频段设计&#xff08;2.4GHz 和 5.8GHz&#xff09;&#xff0c;主要是为了解决以下问题并优化性…

HTTP非流式请求 vs HTTP流式请求

文章目录 HTTP 非流式请求 vs 流式请求一、核心区别 服务端代码示例&#xff08;Node.js/Express&#xff09;非流式请求处理流式请求处理 客户端请求示例非流式请求&#xff08;浏览器fetch&#xff09;流式请求处理&#xff08;浏览器fetch&#xff09; Python客户端示例&…

react native中如何实现吸顶的效果

rn中实现吸顶效果用ScrollView、SectionList、FlatList都可以实现&#xff0c;因为SectionList、FlatList都是继承自ScrollView&#xff0c;都会有stickyHeaderIndices属性&#xff0c;这个属性是一个数组&#xff0c;可以决定下标为几的组件有吸顶的效果。 <FlatListdata{…

【EB-06】SystemCreator dbc转arxml

SystemCreator dbc转arxml 1. SystemCreator 意义2. SystemCreator使用方法2.1 实现步骤2.2 参考官方文档方法1. SystemCreator 意义 EB Tresos 对dbc直接导入的支持不是很完善,dbc也不是AUTOSAR标准的数据库文件,EB建议所有通信矩阵通过ARXML交互比较合理(AUTOSAR定义的)…

idea中或pycharm中编写Markdown文件

参考 ltjt_aiseek: seek_backend_py 项目 数智科技ai探索API接口开发 1. 安装 Django 框架 在开始创建 Django 项目之前&#xff0c;需要先安装 Django 框架。可以通过 PyCharm 的终端或者系统的命令行工具来完成安装。 使用 PyCharm 终端安装 打开 PyCharm&#xff0c;如果…

J-LangChain - RAG - PDF问答

系列文章索引 J-LangChain 入门 在现代自然语言处理&#xff08;NLP&#xff09;中&#xff0c;基于文档内容的问答系统变得愈发重要&#xff0c;尤其是当我们需要从大量文档中提取信息时。通过结合文档检索和生成模型&#xff08;如RAG&#xff0c;Retrieval-Augmented Gener…