C++ Primer(第五版) 16.5节练习

16.62    Sales_data类要包含==运算符,主程序代码如下:

#include "Sales_data.h"
#include <unordered_set>

using namespace std;

namespace std {
	template <>
	struct hash<Sales_data>
	{
		typedef size_t result_type;
		typedef Sales_data argument_type;
		size_t operator()(const Sales_data& s) const;
	};
	
	size_t
	hash<Sales_data>::operator()(const Sales_data &s) const
	{
		return hash<string>()(s.bookNo) ^
			   hash<unsigned>()(s.units_sold) ^
			   hash<double>()(s.revenue);
	}
}

int main()
{
	unordered_multiset<Sales_data> SDset;
	Sales_data item;
	
	while (read(cin, item)) {
		SDset.insert(item);
	}
	cout << SDset.size() << endl;
	for (auto sd : SDset)
	{
    	print(cout, sd) << endl;
    }

	return 0;
}

16.63    

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

using namespace std;

template <typename T>
size_t count(vector<T> &v, const T &t)
{
	size_t ret = 0;
	for (auto ev : v) {
		if (t == ev)
			++ret;
	}
	
	return ret;
}

template <>
size_t count(vector<const char*> &v, const char* const &p)
{
	size_t ret = 0;
	for (auto ev : v) {
		if (!strcmp(ev, p))
			++ret;
	}
	
	return ret;
}

int main()
{
    vector<double> vd = { 1.1, 3.14, 2.2, 3.14, 3.3, 4.4};
    cout << count(vd, 3.14) << endl;

    vector<int> vi = { 0, 1, 2, 3, 4, 5 };
    cout << count(vi, 0) << endl;

    vector<string> vs = { "Hello", "World", "!" };
    cout << count(vs, string("end")) << endl;
	
	string s1("cat");
	string s2("dog");
	string s3("rat");
	
	const char *p1 = s1.c_str();
	const char *p2 = s2.c_str();
	const char *p3 = s3.c_str();
	const char *p4 = s2.c_str();
	
	vector<const char *> vp;
	vp.push_back(p1);
	vp.push_back(p2);
	vp.push_back(p3);
	vp.push_back(p4);
	
	cout << count(vp, p2) << endl;

    return 0;
}

16.64    已包含在上题代码中

16.65    

template <>
string debug_rep(char *p)
{
	return debug_rep(string(p));
}

template <>
string debug_rep(const char *cp)
{
	return debug_rep(string(cp));
}

16.66    当不能或不希望使用通用模板版本时,可以定义类或函数的特例化版本;对重载而言,在函数匹配过程中会在重载函数中选择最佳匹配,需要小心设计,避免实际匹配不符合预期。

16.67    特例化版本不会影响函数匹配,只是接管实例化工作,当某个模板是最佳匹配,且将其实例化为该特殊实例时,不再从原模板实例化,而直接使用特例化版本。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值