三元組是由任意三個實數構成的序列。本實驗要求實現一個泛型類別 Triple,支援以下基本操作:
採用 C++ 模板實現,支援任意數值型別:
#include <iostream>
using namespace std;
template <class Elem>
class Triple {
private:
Elem e1, e2, e3;
public:
Triple(Elem v1, Elem v2, Elem v3) : e1(v1), e2(v2), e3(v3) {}
Elem Get(int i) {
if (i >= 1 && i <= 3) {
Elem a[3] = {e1, e2, e3};
return a[i-1];
}
cout << "錯誤,輸入值範圍是 1~3" << endl;
return Elem(); // 預設值
}
bool Put(int i, Elem e) {
if (i >= 1 && i <= 3) {
if (i == 1) e1 = e;
else if (i == 2) e2 = e;
else e3 = e;
return true;
}
return false;
}
Elem GetMax() {
Elem a[3] = {e1, e2, e3};
Elem max = a[0];
if (a[1] > max) max = a[1];
if (a[2] > max) max = a[2];
return max;
}
Elem GetMin() {
Elem a[3] = {e1, e2, e3};
Elem min = a[0];
if (a[1] < min) min = a[1];
if (a[2] < min) min = a[2];
return min;
}
void Output() {
Elem a[3] = {e1, e2, e3};
cout << "目前三元組所有分量值為:";
for (int i = 0; i < 3; ++i) cout << a[i] << " ";
cout << endl;
}
Elem Sum(int i, int j) {
Elem a[3] = {e1, e2, e3};
return a[i-1] + a[j-1];
}
void Proportion(Elem a, Elem b, Elem c) {
e1 *= a; e2 *= b; e3 *= c;
}
void Destroy() {
e1 = e2 = e3 = 0;
cout << "三元組已初始化為 0" << endl;
}
};
int main() {
Triple<float> t(10, 33, -44);
cout << "測試結果:" << endl;
cout << "第一個數為:" << t.Get(1) << endl;
t.Output();
cout << "\n將第一個數修改為 55 後" << endl;
t.Put(1, 55);
t.Output();
cout << "\n最大值:" << t.GetMax() << endl;
cout << "最小值:" << t.GetMin() << endl;
cout << "第一和第三個數的和:" << t.Sum(1, 3) << endl;
cout << "\n各元素分別乘以 0.1, 0.4, 0.5 後" << endl;
t.Proportion(0.1, 0.4, 0.5);
t.Output();
cout << "\n銷毀三元組" << endl;
t.Destroy();
t.Output();
return 0;
}
Proportion 允許三個不同比例因子,比單一因子更靈活