三元组Triplet的C++代码(类)实现

C++实现

#include<iostream>
using namespace  std;

typedef 
char
 ElemType;

class
 Triplet
{
public
:
  Triplet(ElemType v1,ElemType v2,ElemType v3);
  
~
Triplet();
  ElemType Get(
intconst
;
  
void Put(int
,ElemType);
  
bool IsAscending() const
;
  
bool IsDescending() const
;
  ElemType Min() 
const
;
  ElemType Max() 
const
;
private
:
  ElemType 
*
T;
};

Triplet::Triplet(ElemType e1,ElemType e2,ElemType e3)
{
  cout
<<"In the Triplet Constructor"<<
endl;
  T
=new ElemType[3
];
  T[
0]=
e1;
  T[
1]=
e2;
  T[
2]=
e3;
}

Triplet::
~
Triplet()
{
  cout
<<"In the Triplet Destructor"<<
endl;
  delete [] T;
}

ElemType Triplet::Get(
int i) const

{
  
if (i<1||i>3throw  i;
  
return T[i-1
];
}

void Triplet::Put(int
 i,ElemType e)
{
  
if (i<1||i>3throw
 i;
  T[i
-1]=
e;
}

bool Triplet::IsAscending() const

{
  
return (T[0]<=T[1])&&(T[1]<=T[2 ]);
}

bool Triplet::IsDescending() const

{
  
return (T[0]>=T[1])&&(T[1]>=T[2 ]);
}

ElemType Triplet::Min() 
const

{
  
return T[0]<=T[1]?(T[0]<=T[2]?T[0]:T[2]):(T[1]<=T[2]?T[1]:T[2 ]);
}

ElemType Triplet::Max() 
const

{
  
return T[0]>=T[1]?(T[0]>=T[2]?T[0]:T[2]):(T[1]>=T[2]?T[1]:T[2 ]);
}

ostream
&operator<<(ostream&output,const Triplet&
T)
{
  output
<<"Triplet:["<<T.Get(1)<<","<<T.Get(2)<<","<<T.Get(3)<<"]"<<
endl;
  
return
 output;
}

int
 main()
{
  Triplet T1(
'A','B','C'
);
  
try

  {
    cout
<< T1;
    cout
<<"Elem 1:"<<T1.Get(1)<<
endl;
    cout
<<"Elem 2:"<<T1.Get(2)<<
endl;
    cout
<<"Elem 3:"<<T1.Get(3)<<
endl;
    T1.Put(
3,'D'
);
    cout
<<
T1;
    cout
<<"IsAscending:"<<T1.IsAscending()<<
endl;
    cout
<<"IsDescending:"<<T1.IsDescending()<<
endl;
    cout
<<"Min Elem:"<<T1.Min()<<
endl;
    cout
<<"Max Elem:"<<T1.Max()<<
endl;
    T1.Put(
4,'M'
);
  }
  
catch(int
)
  {
    cout
<<"Error:Triplet Access Overflow"<<
endl;
  }
  
return 0
;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

learnlife

向这个世界输出我独有的声音。

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

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

打赏作者

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

抵扣说明:

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

余额充值