C++ Primer (第五版)第六章习题部分答案

        在我自学C++过程中,我选择了C++Primer这本书,并对部分代码习题进行了求解以及运行结果。接下来几个月我将为大家定时按章节更新习题答案与运行结果,运行环境(Visual Studio Code,windows 11):

C++ Primer (第五版)习题答案总目录:

https://blog.csdn.net/weixin_48467622/article/details/136418131?spm=1001.2014.3001.5501

6.1 实参和形参的区别的什么?

形参在函数的定义中声明;
实参是形参的初始值。

6.2 请指出下列函数哪个有错误,为什么?应该如何修改这些错误呢?

(a) int f() {
          string s;
          // ...
          return s;
    }
(b) f2(int i) { /* ... */ }
(c) int calc(int v1, int v1) { /* ... */ }
(d) double square (double x)  return x * x; 

(a)函数声明返回类型为int,实际返回类型为string:

string f() {  // return should be string, not int
          string s;
          // ...
          return s;
}

(b)需要加上函数类型声明:

void f2(int i) { /* ... */ }  // function needs return type

(c)形参的名字不能相同:

int calc(int v1, int v2) { /* ... */ }  // parameter list cannot use same name twice

(d)需要有大括号(函数块):

double square (double x) { return x * x; }  // function body needs braces

6.3 编写你自己的fact函数,上机检查是否正确。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>

#include <iterator>
using namespace std;

int fact(int val)
{
	int ret = 1;
	while (val > 1)
	{
		ret *= val;
		val--;
	}
	return ret;
}
int main()
{
	int j = fact(5);
	cout << j << endl;
	return 0;
}

6.4 编写一个与用户交互的函数,要求用户输入一个数字,计算生成该数字的阶乘。在main函数中调用该函数。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>

#include <iterator>
using namespace std;

int fact(int val)
{
	int ret = 1;
	while (val > 1)
	{
		ret *= val;
		val--;
	}
	return ret;
}
int main()
{
	int n;
	cin >> n;
	int j = fact(n);
	cout << j << endl;
	return 0;
}

6.5 编写一个函数输出其实参的绝对值。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>

#include <iterator>
using namespace std;

int abs(int val)
{
	int ret;
	if (val >= 0)
	{
		ret = val;
	}
	else
	{
		ret = -val;
	}
	return ret;
}
int main()
{
	int n;
	cin >> n;
	int j = abs(n);
	cout << j << endl;
	return 0;
}

6.6 说明形参、局部变量以及局部静态变量的区别。编写一个函数,同时达到这三种形式。

形参:定义在函数形参列表里面;

局部变量:定义在代码块里面;

局部静态变量:在程序的执行路径第一次经过对象定义语句时初始化,并且直到程序终止时才被销毁。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>

#include <iterator>
using namespace std;

size_t cadd(int val)//val是一个形参和局部变量
{
	static size_t ctr = 0;//ctr是一个局部静态变量
	ctr += val;
	return ctr;
}
int main()
{
	for (int i = 0; i < 10; i++)//i是一个局部变量
	{
		cout << cadd(i) << endl;
	}
	return 0;
}

6.7 编写一个函数,当它第一次被调用时返回0,以后每次被调用返回值加1。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>

#include <iterator>
using namespace std;

size_t count_calls()
{
	static size_t ctr = 0;
	return ctr++;
}
int main()
{
	for (int i = 0; i < 10; i++)//i是一个局部变量
	{
		cout << count_calls() << endl;
	}
	return 0;
}

6.8 编写一个名为Chapter6.h 的头文件,令其包含6.1节练习中的函数声明。

#pragma once
#ifndef CHAPTER6_H
#define CHAPTER6_H

int fact(int val);
int abs(int val);

#endif

6.9 编写你自己的fact.cc 和factMain.cc ,这两个文件都应该包含上一小节的练习中编写的 Chapter6.h 头文件。通过这些文件,理解你的编译器是如何支持分离式编译的。

Chapter.h

#pragma once
#ifndef CHAPTER6_H
#define CHAPTER6_H

int fact(int val);
int abs1(int val);

#endif

fact.cpp

#include "Chapter.h"

int fact(int val)
{
	int ret = 1;
	while (val > 1)
	{
		ret *= val;
		val--;
	}
	return ret;
}

int abs1(int val)
{
	int ret;
	if (val >= 0)
	{
		ret = val;
	}
	else
	{
		ret = -val;
	}
	return ret;
}

factMain.cpp

#include "Chapter.h"
#include<iostream>
using namespace std;

int main()
{
	cout << fact(6) << endl;
	cout << abs1(-6) << endl;
	return 0;
}

6.10 编写一个函数,使用指针形参交换两个整数的值。在代码中调用该函数并输出交换后的结果,以此验证函数的正确性。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>

#include <iterator>
using namespace std;

void swap(int* a, int* b)
{
	int t = *a;
	*a = *b;
	*b = t;
}
int main()
{
	int x = 6, y = 66;
	cout << x << " " << y << endl;
	swap(&x, &y);
	cout << x << " " << y << endl;
	return 0;
}

6.11 编写并验证你自己的reset函数,使其作用于引用类型的参数。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>

#include <iterator>
using namespace std;

void reset(int& i)
{
	i = 66;
}
int main()
{
	int val = 60;
	cout << val << endl;
	reset(val);
	cout << val << endl;
	return 0;
}

6.12 改写6.2.1节练习中的程序,使其引用而非指针交换两个整数的值。你觉得哪种方法更易于使用呢?为什么?

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>

#include <iterator>
using namespace std;

void swap(int& a, int& b)
{
	int t = a;
	a = b;
	b = t;
}
int main()
{
	int x = 6, y = 66;
	cout << x << " " << y << endl;
	swap(x, y);
	cout << x << " " << y << endl;
	return 0;
}

引用更易于使用,不用考虑传递的是指针,避免语法错误;
使用引用避免拷贝。

6.13 假设 T 是某种类型的名字,说明以下两个函数声明的区别:一个是void f(T), 另一个是 void f(&T)。

void f(T)
将实参的值拷贝后赋给形参,不能通过改变形参的值来改变实参;
void f(&T)
使用引用将形参绑定到实参上,可以通过改变形参来改变实参。

6.14 举一个形参应该是引用类型的例子,再举一个形参不能是引用类型的例子。

应该是引用:

void reset(int &i)
{
        i = 0;
}

不能是引用:

void print(std::vector<int>::iterator begin, std::vector<int>::iterator end)
{
        for (std::vector<int>::iterator iter = begin; iter != end; ++iter)
                std::cout << *iter << std::endl;
}

6.15 说明find_char 函数中的三个形参为什么是现在的类型,特别说明为什么s是常量引用而occurs是普通引用?为什么s和occurs是引用类型而c不是?如果令s是普通引用会发生什么情况?如果令occurs是常量引用会发生什么情况?

s不需要改变实参,occurs需要改变实参;s可能会很大,occurs需要改变实参,c没有上述两个需求;如果s是普通的引用可能改变实参;occurs是常量引用则不能改变实参,++occurs会报错。

6.16 下面的这个函数虽然合法,但是不算特别有用。指出它的局限性并设法改善。

bool is_empty(string& s) { return s.empty(); }

该函数无需改变实参,故将其设置为const比较好,这样也可以传入const类型的字符串,或字符串字面值。

bool is_empty(const string& s) { return s.empty(); }

6.17 编写一个函数,判断string对象中是否含有大写字母。编写另一个函数,把string对象全部改写成小写形式。在这两个函数中你使用的形参类型相同吗?为什么?

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>

#include <iterator>
using namespace std;

bool isupper(const string& s)
{
	for (auto c : s)
	{
		if (isupper(c))
		{
			return true;
		}
	}
	return false;
}

void toupper(string& s)
{
	for (auto& c : s)
	{
		c = tolower(c);
	}
}
int main()
{
	string s1 = "Hello The USA!";
	cout << isupper(s1) << endl;
	cout << s1 << endl;
	toupper(s1);
	cout << s1 << endl;
	return 0;
}

6.18 为下面的函数编写函数声明,从给定的名字中推测函数具备的功能。

  • (a) 名为 compare 的函数,返回布尔值,两个参数都是 matrix 类的引用。
  • (b) 名为 change_val 的函数,返回vector的迭代器,有两个参数:一个是int,另一个是vector的迭代器
(a)bool compare(matrix &m1,matrix &m2);
(b)vector<int>::iterator change_val(int i,vector<int>::iterator);

6.19 假定有如下声明,判断哪个调用合法、哪个调用不合法。对于不合法的函数调用,说明原因。

double calc(double);
int count(const string &, char);
int sum(vector<int>::iterator, vector<int>::iterator, int);
vector<int> vec(10);
(a) calc(23.4, 55.1);
(b) count("abcda",'a');
(c) calc(66);
(d) sum(vec.begin(), vec.end(), 3.8);

(a)不合法,只能一个形参;
(b)合法;
(c)合法;
(d)合法。

6.20 引用形参什么时候应该是常量引用?如果形参应该是常量引用,而我们将其设为了普通引用,会发生什么情况?

无需改变实参的时候应该用常量引用;可能会改变常亮实参,从而导致出错。

6.21 编写一个函数,令其接受两个参数:一个是int型的数,另一个是int指针。函数比较int的值和指针所指的值,返回较大的那个。在该函数中指针的类型应该是什么?

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>

#include <iterator>
using namespace std;

void comp(int a, int* b)
{
	cout << ((a > *b) ? a : *b )<< endl;
}
int main()
{
	int x = 1, i = 3;
	int* y = &i;
	comp(x, y);
	return 0;
}

int型

6.22 编写一个函数,令其交换两个int指针。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>

#include <iterator>
using namespace std;

void swap(int* &a, int* &b)
{
	int* t;
	t = a;
	a = b;
	b = t;
}
int main()
{
	int a = 6, b = 66;
	int* i = &a, * j = &b;
	cout << *i << " " << *j << endl;
	swap(i, j);
	cout << *i << " " << *j << endl;
	return 0;
}

6.23 参考本节介绍的几个print函数,根据理解编写你自己的版本。依次调用每个函数使其输入下面定义的i和j:

int i = 0 , j[2] = {0 , 1};
#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>

#include <iterator>
using namespace std;

void print1(const int a, const int *b)
{
	cout << "print1:" << endl;
	cout << "i:" << a << endl;
	cout << "j:" << endl;
	for(int i=0;i<2;i++)
	{
		cout << *b++ << " ";
	}
	cout << endl;
}
void print2(const int a, const int b[])
{
	cout << "print2:" << endl;
	cout << "i:" << a << endl;
	cout << "j:" << endl;
	for (int i = 0; i < 2; i++)
	{
		cout << *b++ << " ";
	}
	cout << endl;
}
void print3(const int a, const int b[2])
{
	cout << "print3:" << endl;
	cout << "i:" << a << endl;
	cout << "j:" << endl;
	for (int i = 0; i < 2; i++)
	{
		cout << *b++ << " ";
	}
	cout << endl;
}
int main()
{
	int i = 0, j[2] = { 0,1 };
	print1(i, j);
	print2(i, j);
	print3(i, j);
	return 0;
}

6.24 描述下面这个函数的行为。如果代码中存在问题,请指出并改正。

void print(const int ia[10])
{
	for (size_t i = 0; i != 10; ++i)
		cout << ia[i] << endl;
}

该函数传递的不是数组是const int*,如果实参不是含10个元素的int数组,可能导致for循环数组越界。修改为:

void print(const int (&ia)[10])
{
	for (size_t i = 0; i != 10; ++i)
		cout << ia[i] << endl;
}

6.25 编写一个main函数,令其接受两个实参。把实参的内容连接成一个string对象并输出出来。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>

#include <iterator>
using namespace std;

int main(int argc,char const *argv[])
{
	cout << "argc:" << argc << endl;
	string a1 = argv[1], a2 = argv[2], a3 = argv[3];
	cout << a1 + a2 + a3<< endl;
	return 0;
}

6.26 编写一个程序,使其接受本节所示的选项;输出传递给main函数的实参内容。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>

#include <iterator>
using namespace std;

int main(int argc,char const *argv[])
{
	cout << "argc:" << argc << endl;
	for (int i = 0; i < argc; i++)
	{
		cout << argv[i] << " ";
	}
	cout << endl;
	return 0;
}

6.27 编写一个函数,它的参数是initializer_list类型的对象,函数的功能是计算列表中所有元素的和。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>
#include <initializer_list>
#include <iterator>
using namespace std;
int count_int(initializer_list<int> i1)
{
	int cnti = 0;
	for (auto i : i1)
	{
		cnti += i;
	}
	return cnti;
}
int main()
{
	cout << count_int({ 1,2,3,4,5,6,7 }) << endl;
	return 0;
}

6.29 在范围for循环中使用initializer_list对象时,应该将循环控制变量声明成引用类型吗?为什么?

如果拷贝代价小,则无需设置成引用类型;如果拷贝代价大,可以设置成引用类型。

6.30 编译第200页的str_subrange函数,看看你的编译器是如何处理函数中的错误的。

错误#1:error: return-statement with no value, in function returning ‘bool’ [-fpermissive]
错误#2:检查不出,返回true

6.31 什么情况下返回的引用无效?什么情况下返回常量的引用无效?

返回的引用时局部对象的引用,返回的常量引用是局部常量对象的引用时。

6.32 下面的函数合法吗?如果合法,说明其功能;如果不合法,修改其中的错误并解释原因。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>
#include <initializer_list>
#include <iterator>
using namespace std;
int& get(int* array, int index) 
{ 
    return array[index];
}
int main()
{
    int ia[10];
    for (int i = 0; i != 10; ++i)
        get(ia, i) = i;
    for (auto j : ia)
        cout << j << " ";
    cout << endl;
}

6.33 编写一个递归函数,输出vector对象的内容。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>
#include <initializer_list>
#include <iterator>
using namespace std;
void CoutVector(vector<int>::const_iterator iter_begin, vector<int>::const_iterator iter_end)
{
    if (iter_begin != iter_end)
    {
        cout << *iter_begin << " ";
        CoutVector(++iter_begin, iter_end);
    }
    else
    {
        cout << endl;
        return;
    }
}
int main()
{
    vector<int> v{ 1,2,3,4,5,6,7,8,9 };
    CoutVector(v.begin(), v.end());
    return 0;
}

6.34 如果factorial 函数的停止条件如下所示,将发生什么?

if (val != 0)

如果实参为大于等于0,函数将会多乘以一个1,比如factorial(5),等价于5 * 4 * 3 * 2 * 1 * 1;
如果实参小于0,函数将会不断地调用它自身直到程序栈空间耗尽为止。

6.35  在调用factorial函数时,为什么我们传入的值是 val-1 而非 val--

val--会返回未修改的val内容,使程序陷入无限循环;val--会修改val的内容,使程序运行结果不符合预期。

6.36 编写一个函数声明,使其返回数组的引用并且该数组包含10个string对象。不用使用尾置返回类型、decltype或者类型别名。

string (&func(string (&arr)[10]))[10];

6.37 为上一题的函数再写三个声明,一个使用类型别名,另一个使用尾置返回类型,最后一个使用decltype关键字。你觉得哪种形式最好?为什么?

using arrt = string[10];
arrt &func(arrt &arrs);
auto func(atring a)->string(&)[10];
string a[10];
decltype(a) &func(string qq);

6.38 修改arrPtr函数,使其返回数组的引用。

decltype(odd)& arrPtr(int i)
{
          return (i % 2) ? odd : even;
}

6.39 说明在下面的每组声明中第二条语句是何含义。如果有非法的声明,请指出来。

(a) int calc(int, int);
	int calc(const int, const int);
(b) int get();
	double get();
(c) int *reset(int *);
	double *reset(double *);

(a)非法,重复声明可以,重复定义不行,第二个非引用非指针;

(b)非法,仅返回值不同;
(c)合法,重载关系。

6.40 下面的哪个声明是错误的?为什么?

(a) int ff(int a, int b = 0, int c = 0);
(b) char *init(int ht = 24, int wd, char bckgrnd);		

(a)正确

(b)因为一旦某个形参被赋予了默认值,那么它之后的形参都必须要有默认值。

6.41 下面的哪个调用是非法的?为什么?哪个调用虽然合法但显然与程序员的初衷不符?为什么?

char *init(int ht, int wd = 80, char bckgrnd = ' ');
(a) init();
(b) init(24,10);
(c) init(14,'*');

(a)非法,函数第一个形参没有默认实参,必须给实参;
(b)合法;
(c)合法,但与初衷不符,char '*'转换成整形了。

6.42 给make_plural函数的第二个形参赋予默认实参’s’, 利用新版本的函数输出单词success和failure的单数和复数形式。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>
#include <initializer_list>
#include <iterator>
using namespace std;

string make_plural(size_t ctr, const string& word, const string& ending = "s")
{
    return (ctr > 1) ? word + ending : word;
}
int main()
{
    cout << make_plural(2, "success", "es") << endl;
    cout << make_plural(2, "failture") << endl;
    return 0;
}

6.43 你会把下面的哪个声明和定义放在头文件中?哪个放在源文件中?为什么?

(a) inline bool eq(const BigInt&, const BigInt&) {...}
(b) void putValues(int *arr, int size);

(a)放在头文件中,内联函数在程序中可以多次定义,它的多个定义必须完全一致,所以放在头文件中比较好;
(b)放在头文件中,声明放在头文件中。

6.44 将6.2.2节的isShorter函数改写成内联函数。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>
#include <initializer_list>
#include <iterator>
using namespace std;

inline bool inShorter(const string& s1, const string& s2)
{
    return s1.size() < s2.size();
}
int main()
{
    string s1("aaadd"), s2("dadaddf");
    cout << inShorter(s1, s2);
    return 0;
}

6.45 回顾在前面的练习中你编写的那些函数,它们应该是内联函数吗?如果是,将它们改写成内联函数;如果不是,说明原因。

6.38和6.42应该是内联函数;6.4不应该是,规模不小,调用不频繁。

6.46 能把isShorter函数定义成constexpr函数吗?如果能,将它改写成constxpre函数;如果不能,说明原因。

不能,因为std::string::size(); 不是一个constexpr函数,s1.size() == s2.size(); 不是一个常量表达式。

6.47 改写6.3.2节练习中使用递归输出vector内容的程序,使其有条件地输出与执行过程有关的信息。例如,每次调用时输出vector对象的大小。分别在打开和关闭调试器的情况下编译并执行这个程序。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>
#include <initializer_list>
#include <iterator>
using namespace std;
void CoutVector(vector<int>::const_iterator iter_begin, vector<int>::const_iterator iter_end)
{
    #ifndef NDEBUG
        cerr << iter_end - iter_begin << __func__ << " " << __FILE__ << " "
        << __LINE__ << " " << __TIME__ << " " << __DATE__ << endl;
    #endif
    if (iter_begin != iter_end)
    {
        cout << *iter_begin << " ";
        CoutVector(++iter_begin, iter_end);
    }
    else
    {
        cout << endl;
        return;
    }
}
int main()
{
    vector<int> v{ 1,2,3,4,5,6,7,8,9 };
    CoutVector(v.begin(), v.end());
    return 0;
}

打开调试器:

关闭调试器:

6.49 什么是候选函数?什么是可行函数?

候选函数具备两个特征:一是与被调用的函数同名,二是其声明在调用点可见。
可行函数是从候选函数中选出的,有两个特征:一是其形参数量与本次调用提供的实参数量相等,二是每个实参的类型与对应的形参类型相同,或者能转换成形参的类型。

6.51 编写函数f的4版本,令其各输出一条可以区分的消息。验证上一个练习的答案,如果你的回答错了,反复研究本节内容直到你弄清自己错在何处。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>
#include <initializer_list>
#include <iterator>
using namespace std;
void f()
{
    cout << "Function is f()" << endl;
}

void f(int)
{
    cout << "Function is f(int)" << endl;
}

void f(int , int)
{
    cout << "Function is f(int ,int)" << endl;
}

void f(double,double = 3.14)
{
    cout << "Function is f(double,double = 3.14)" << endl;
}
int main()
{
    f();
    f(1);
    f(1, 2);
    f(1.1);
    return 0;
}

6.54 编写函数的声明,令其接受两个int形参并返回类型也是int;然后声明一个vector对象,令其元素是指向该函数的指针。

vector<int (*)(int, int)> vf;

//others:
int func(int a, int b);

using pFunc1 = decltype(func) *;
typedef decltype(func) *pFunc2;
using pFunc3 = int (*)(int a, int b);
using pFunc4 = int(int a, int b);
typedef int(*pFunc5)(int a, int b);
using pFunc6 = decltype(func);

vector<pFunc1> vec1;
vector<pFunc2> vec2;
vector<pFunc3> vec3;
vector<pFunc4*> vec4;
vector<pFunc5> vec5;
vector<pFunc6*> vec6;

6.55 编写4个函数,分别对两个int值执行加、减、乘、除运算;在上一题创建的vector对象中保存指向这些函数的指针。

int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
int divide(int a, int b) { return b != 0 ? a / b : 0; }

6.56 调用上述vector对象中的每个元素并输出结果。

#include <iostream>
#include <cstring>
#include <vector>
#include <stdexcept>
#include <initializer_list>
#include <iterator>
using namespace std;
int add(int a, int b) 
{ 
    return a + b;
}
int subtract(int a, int b) 
{ 
    return a - b; 
}
int multiply(int a, int b) 
{ 
    return a * b; 
}
int divide(int a, int b) 
{ 
    return b != 0 ? a / b : 0; 
}

int main()
{
    vector<int(*)(int, int)> vf;
    vf = { add,subtract,multiply,divide };
    for (auto& c : vf)
    {
        cout << c(6, 3) << endl;
    }
    return 0;
}

  • 8
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Joey.Chao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值