【东华大学oj】顺序表ADT模板简单应用算法设计:在给定的顺序表中找出最大和最小的元素

顺序表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;
}

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ixll625

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值