C++程序设计(PEARSON版)第三版12.2答案

本文介绍了一种使用C++模板函数实现的顺序搜索算法,该算法可以用于不同数据类型如int、double和string的数组中查找指定元素的位置。通过具体示例展示了如何正确调用模板函数,并特别强调了在处理string类型时的注意事项。

(顺序搜索)重写程序清单7-9中的顺序搜索函数,改写为通用函数。用int、double、string数组测试这个函数

一定一定一定要注意对string类型的传值时的特殊处理,一定要像string(“ANP”)这样,否则函数传值时只能传地址,这样就白费了。

#include "pch.h"
#include<iostream>
#include<string>
using namespace std;
template<typename T>
int SearchCertain(T shuzu[], const int size, T key)
{
	for (int i = 0;i < size; i++)
	{
		if (key == shuzu[i])
		{
			return i;
		}
	}
	return -1;
}
int main()
{
	const int n = 5;
	int a[n] = { 1,3,5,7,2 };
	double b[n] = { 1.2,2.4,3.6,10.24,20.48 };
	string c[n] = { "我","爱","黎","慧","珊" };
	if (SearchCertain(a, n, 5)!=-1)
		cout << "位置是:" << SearchCertain(a,n, 5) << endl;
	else
		cout << "int类型没找到!" << endl;
	if (SearchCertain(b,  n, 2.4)!=-1)
		cout << "位置是:" << SearchCertain(b,n, 2.4) << endl;
	else
		cout << "double类型没找到!" << endl;
	if (SearchCertain(c,n,string("Anna"))!=-1)
		cout << "位置是:" << SearchCertain(c,n,string("Anna")) << endl;
	else//一定要加string的这个外套!!!!!
		cout << "string类型没找到!" << endl;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值