首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

C++ 實作三元組抽象資料型態 (Triple ADT) 完整教學

     編輯:關於C

實驗目的:設計並實現「三元組」ADT

三元組是由任意三個實數構成的序列。本實驗要求實現一個泛型類別 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;
}

關鍵點總結

  • 使用模板實現型別無關性
  • 分量索引從 1 開始,內部轉為 0-based 陣列存取
  • 錯誤處理採用回傳布林值或輸出錯誤訊息
  • Proportion 允許三個不同比例因子,比單一因子更靈活
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved