c++ 一个数组数据存放于读取的模板类

#include <bits/stdc++.h>
using namespace std;
const int maxn=100+50;
struct student{
    int id;
    float gpa;
};
template <class T,int n>
class Store
{
private:
    T item[maxn];
    bool haveValue[maxn];
    int len;
public:
    Store();
    T & getElem(int i);
    void putElem(const T &x);
};
template <class T,int n>
Store<T,n>::Store():len(n){
    for(int i=0;i<len;i++)
    {
        haveValue[i]=false;
    }
}

template <class T,int n>
T &Store<T,n>::getElem(int i)
{
    if(!haveValue[i])
    {
        cout<<"No item present!"<<endl;
        exit(1);
    }
    else
    {
        haveValue[i]=false;
    }
    return item[i];
}
template<class T,int n>
void Store <T,n>::putElem(const T &x)
{
    bool check=false;
    for(int i=0;i<len;i++)
    {
       if(!haveValue[i])
       {
           check=true;
           item[i]=x;
           haveValue[i]=true;
           break;
       }
    }
    if(!check)
    {
        cout<<"there is no place to put the element"<<endl;
        return ;
        //exit(1);
    }
}
int main()
{
    Store<int,3>s1;
    s1.putElem(2);
    s1.putElem(5);
    int k=s1.getElem(1);
    cout<<k<<endl;
    Store<double,3>s2;
    s2.putElem(1.7);
    student t1{1000,2.3};
    Store<student,3>s3;
    s3.putElem(t1);
    cout<<"student's id is "<<s3.getElem(0).id<<endl;
    cout<<s1.getElem(3)<<endl;
    return 0;
}
全部评论

相关推荐

牛客162194370号:
点赞 评论 收藏
分享
斑驳不同:还为啥暴躁 假的不骂你骂谁啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务