c++ primer第16章课后习题答案

16.1.1节练习

1. 练习16.1
当我们调用template时,编译器会根据函数实参的类型推断模板实参,从而确定最匹配的绑定到模板参数T的 类型,之后编译器用推断出得模板参数来实例化一个特定函数的版本,这个过程就叫做实例化。

2. 练习16.2
模板函数在.h文件中定义

#ifndef TEMPLATE_COMPARE_H
#define TEMPLATE_COMPARE_H

template<typename T> 
int compare(const T &v1,const T &v2)
{
	if(v1<v2) return -1;
	if(v1>v2) return 1;
	return 0;
}

#endif TEMPLATE_COMPARE_H

main函数里调用

cout<<"result1 "<<compare(1,2)<<endl;
cout<<"result2 "<<compare(2.0,1.0)<<endl;

3. 练习16.3

main函数里执行下述代码,其中Animal类是空类。

Animal a,b;
cout<<"result3 "<<compare(a,b)<<endl;

vs2010里产生两个错误,一个c2784:推导模板参数错误,一个c2676:Animal类没有定义operator <的运算符。

4. 练习16.4
template.h

#ifndef TEMPLATE_FIND_H
#define TEMPLATE_FIND_H

#include <vector>
#include <string>

template <typename U,typename T> 
bool tFind(const U &it1,const U &it2,const T &t)
{
	auto it3 = it1;
	while (it3!=it2){
		if(*it3 == t) return true;
		++it3;
	}
	return false;
}
#endif TEMPLATE_FIND_H

main.cpp

	//因为我用的是vs2010,还不支持C++11的容器直接初始化列表,所以用这种方法初始化
	int a[5] = {1,2,3,4,5};
	vector<int> vec1(a,a+5);

	string b[3] = {"i","love","you"};
	vector<string> vec2(b,b+3);

	bool res1 = tFind(vec1.cbegin(),vec1.cend(),4);
	cout<<res1<<endl;
	bool res2 = tFind(vec2.cbegin(),vec2.cend(),"i");
	cout<<res2<<endl;

5. 练习16.5

template <typename T> 
void print(const T &vec,size_t n)
{
	int i = 0;
	while (i!=n){
		cout<<vec[i++]<<endl;	
	}
}

6. 练习16.6 练习16.7

begin()是一个模版函数,接受一个容器的引用,返回指向容器第一个元素的迭代器

end()是一个模版函数,接受一个容器的引用,返回指向容器最后一个元素下一个地方的迭代器

template.h

template <typename T,unsigned N>
const T* tbegin(const T (&vec)[N])
{
	return vec;
}
template <typename T,unsigned N>
const T* tend(const T (&vec)[N])
{
	return vec+N;
}
template <typename T,unsigned N>
size_t tsize(const T (&vec)[N])
{
	return N;
}

main.cpp

int a[5] = {1,2,3,4,5};
cout<<tsize(a)<<endl;
 const int *it = NULL;
for (it=tbegin(a);it!=tend(a);++it){
	cout<<*it<<endl;
}

7. 练习16.8
并非所有的容器都定义了operate <,但C++标准库的所有容器都定义了operate ==和!=。

16.1.2节练习

1.练习16.9
类模版:用来生成类的蓝图,与函数模版不同的是,编译器不能为类模版推断模版参数类型,所以在实参列表中,类模版需要做的更多,类模版就是生成类的实例,函数模版就是用来生成函数的实例。

2.练习16.10
编译器会重写类模板,将模板参数T的每个实例替换为给定的模板实参(显式)。

3.练习16.11
在List类内,使用模版名不需要再加参数列表,而ListItem使用时必须加上<>模版参数列表

4.练习16.12

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值