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

被折叠的 条评论
为什么被折叠?



