# 一次遍历返回序列的最大值和次大值

/***************************************************************

File Name: find_max_premax_value.cpp
Author: tony
Mail: 445241843@qq.com
Created Time: 2016骞?8鏈?3鏃?鏄熸湡鍏?10鏃?6鍒?4绉? **************************************************************/

#include<iostream>
#include<ctime>
#include<vector>
using namespace std;

const int ARRAY_LENGTH = 20;
const int NUM_RANGE = 100;

template
vector& create_array(void);

template
bool find_max_premax_value(vector& arr, T & max, T & premax);

int main()
{
int max = 0, premax = 0;
vector arr = create_array();
for(auto x : arr)
cout << x << ‘\t’;
cout << endl;

if(find_max_premax_value(arr, max, premax))
cout << "max = " << max << " . premax = " << premax << endl;


}

template
vector& create_array(void)
{
vector arr;
srand(static_cast(time(0)));
for(int i = 0; i < ARRAY_LENGTH;++i)
{
arr.push_back(rand() % NUM_RANGE);
}
return arr;
}

template
bool find_max_premax_value(vector& arr, T & max, T & premax)
{
if(arr.size() >= 3)
{
if(arr[1] < arr[2])
{
max = arr[2];
premax = arr[1];
}
else
{
max = arr[1];
premax = arr[2];
}

    for(int i = 3; i < arr.size(); ++i)
{
if(arr[i] > max)
{
premax = max;
max = arr[i];
}
else
{
if(arr[i] > premax)
premax = arr[i];
}
}
return true;
}
else
return false;


}