求数组中的最大值和最小值(不用现成的api)
使用模板声明函数类型
#include<iostream>
#include<vector>
using namespace std;
template<typename T>
void minmaxValue(const T v1, const T v2, T&min, T&max)
{
if (v1 <= v2)
{
min = v1;
max = v2;
}
else
{
min = v2;
max = v1;
}
}
template<typename T1, typename T2>
void myMinMax(typename T1 vt, T2& min, T2& max)
{
//初始化min和max;
auto vtI = vt.begin();
minmaxValue(*vtI, *(vtI + 1), min, max);
//如果元素为基数,则从第二个值开始
if (vt.size() % 2 != 0) vtI++;
for (; vtI != vt.end(); vtI += 2)
{
if (*vtI <= *(vtI + 1))
{
if (*vtI<min) min = *vtI;
if (*(vtI + 1)>max) max = *(vtI + 1);
}
else
{
if (*(vtI + 1)<min) min = *(vtI + 1);
if (*vtI>max) max = *vtI;
}
}
}
void test()
{
//初始化数组
int a[10] =
{ 32,12,5,99,1,5,9,12,19,23 };
vector<int> vtd(a, a + 10);
//前
for (int j = 0; j<10; j++)
{
cout << a[j] << " ";
}
cout << endl << endl;
int myMin = 0;
int myMax = 0;
//调用函数
myMinMax(vtd, myMin, myMax);
//后
cout << "Minimum is: " << myMin << "\nMaximum is: " << myMax << endl;
}
int main()
{
test();
system("pause");
return 0;
}