顺序表ADT模板简单应用算法设计:在给定的顺序表中找出最大和最小的元素
时间限制: 1s
类别: DS:线性表->顺序表--简单
问题描述
目的:使用自行设计的顺序表ADT或STL的vector模板设计并实现顺序表应用场合的一些简单算法设计。
应用8:试设计一个算法,找出顺序表A中最大和最小的元素(输出在屏幕上),并保持原顺序表不变。
(1)顺序表ADT版本
参考函数原型:
template<class ElemType>
bool Search_Max_Min( const SqList<ElemType> &A, ElemType &max, ElemType &min );
(2)vector版本
参考函数原型:
template<class ElemType>
bool Search_Max_Min( const vector<ElemType> &A, ElemType &max, ElemType &min );
输入说明
第一行:顺序表A的数据元素的数据类型标记(0:int,1:double,2:char,3:string)
第二行:顺序表A的数据元素(数据元素之间以空格分隔)
输出说明
如第一行输入值为0、1、2、3之外的值,直接输出“err”
否则:
第一行:顺序表A的遍历结果
第二行:最大值max
第三行:最小值min
#include <iostream>
#include <vector>
#include <sstream>
#include <limits>
#include <algorithm>
using namespace std;
template<class ElemType>
bool Search_Max_Min( const vector<ElemType> &A, ElemType &max, ElemType &min )
{
max=min=A[0];
for(size_t i=1; i<A.size(); ++i)
{
if(A[i]>max) max=A[i];
if(A[i]<min) min=A[i];
}
return 1;
}
template<typename T>
void printVector(const vector<T>& v)
{
for(size_t i = 0; i < v.size(); ++i)
{
cout << (i > 0 ? "," : "") << v[i];
}
cout << endl;
}
int main()
{
int type;
cin>>type;
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // 忽略换行符
string line;
getline(cin, line); // 读取一行作为顺序表的数据
stringstream ss(line);// 将一行数据放入字符串流中
switch(type)
{
case 0:
{
vector<int> vi;
int temp;
int max,min;
while (ss >> temp) vi.push_back(temp);
printVector(vi);
if(Search_Max_Min(vi,max,min))
{
cout<<max<<endl<<min<<endl;
}
break;
}
case 1:
{
vector<double> vd;
double temp,max,min;
while (ss >> temp) vd.push_back(temp);
printVector(vd);
if(Search_Max_Min(vd,max,min))
{
cout<<max<<endl<<min<<endl;
}
break;
}
case 2:
{
vector<char> vc;
char temp,max,min;
while (ss >> temp) vc.push_back(temp);
printVector(vc);
if(Search_Max_Min(vc,max,min))
{
cout<<max<<endl<<min<<endl;
}
break;
}
case 3:
{
vector<string> vs;
string temp,max,min;
while (ss >> temp) vs.push_back(temp);
printVector(vs);
if(Search_Max_Min(vs,max,min))
{
cout<<max<<endl<<min<<endl;
}
break;
}
default:
cout << "err" << endl;
break;
}
return 0;
}