📄 c_11_1.cpp
字号:
#include "stdafx.h"
#include <iostream>
#include <string>
#include<iomanip>
using namespace std;
template <class Type>
class Search
{
Type A[100];
int n;
public:
Search(){}
Search(Type a[],int i)
{ n=i;
for(int j=0;j<i;j++)
A[j]=a[j];
}
int seek(Type b[],int l,int h,Type x);
friend ostream& operator << <Type>(ostream&, Search&);
};
template <class Type>
ostream& operator << (ostream& out, Search<Type>& date)
{
for (int i=0;i<date.n;i++)
out<<date.A[i]<<" ";
out<<endl;
return out;
}
template <class Type>
int Search<Type>::seek(Type b[],int l,int h,Type x)
{
int m;
if(l>h)
{
cout<<endl<<"对不起,你要查找的元素不存在!"<<endl;
return -1;
}
else
{
m=(l+h)/2;
if(x<b[m])
return (seek(b,l,m-1,x));
else if(x==b[m])
return m;
else
return (seek(b,m+1,h,x));
}
}
void main()
{
char a[]={'a','d','g','i','k','m','n','r','t','z'},d;
Search<char> set1(a,10);
cout<<"数组中的元素有:"<<set1;
cout<<"请输入需要查找的元素:";
cin>>d;
cout<<"元素"<<d<<"的位置是: "<< set1.seek(a,0,9,d)+1<<endl;
int c[]={2,5,9,10,30,55,66,71,88,93,100},e;
Search<int> set2(c,10);
cout<<"数组中的元素有:"<<set2;
cout<<"请输入需要查找的元素:";
cin>>e;
cout<<"元素"<<e<<"的位置是: "<< set2.seek(c,0,9,e)+1<<endl;
cin.get();cin.get(); //等待结束,以便调测程序,可以删除
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -