三元组

#include <iostream>
#include <vector>
#include <string>
using namespace std;

// 三元组结构体
struct Triple {
    int row, col; // 行号、列号(从0开始)
    int val;      // 非零元素值
    Triple(int r = 0, int c = 0, int v = 0) : row(r), col(c), val(v) {}
};

// 稀疏矩阵(三元组存储)
struct SparseMatrix {
    int rows, cols, nums; // 矩阵行数、列数、非零元素数
    vector<Triple> data;  // 三元组列表
    SparseMatrix(int r = 0, int c = 0) : rows(r), cols(c), nums(0) {}
};

// 生成稀疏矩阵的三元组(兼容C++98,用push_back)
SparseMatrix createSparseMatrix(int mat[][4], int rows, int cols) {
    SparseMatrix sm(rows, cols);
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (mat[i][j] != 0) {
                sm.data.push_back(Triple(i, j, mat[i][j]));
                sm.nums++;
            }
        }
    }
    return sm;
}

// 输出三元组(修正循环变量)
void printTriple(const SparseMatrix& sm, const string& name) {
    cout << "稀疏矩阵" << name << "的三元组(行,列,值):" << endl;
    for (vector<Triple>::const_iterator it = sm.data.begin(); it != sm.data.end(); ++it) {
        cout << "(" << it->row << "," << it->col << "," << it->val << ") ";
    }
    cout << "\n(矩阵规模:" << sm.rows << "×" << sm.cols << ",非零元素数:" << sm.nums << ")\n" << endl;
}

// 稀疏矩阵的转置(示例:简单实现,按列遍历)
SparseMatrix transposeSparseMatrix(const SparseMatrix& sm) {
    SparseMatrix tsm(sm.cols, sm.rows);
    tsm.nums = sm.nums;
    for (int j = 0; j < sm.cols; j++) {
        for (vector<Triple>::const_iterator it = sm.data.begin(); it != sm.data.end(); ++it) {
            if (it->col == j) {
                tsm.data.push_back(Triple(it->col, it->row, it->val));
            }
        }
    }
    return tsm;
}

int main() {
    int matA[4][4] = {
        {1, 0, 3, 0},
        {0, 1, 0, 0},
        {0, 0, 1, 0},
        {0, 0, 1, 1}
    };
    SparseMatrix a = createSparseMatrix(matA, 4, 4);
    printTriple(a, "A");

    SparseMatrix aT = transposeSparseMatrix(a);
    printTriple(aT, "A的转置");

    return 0;
}

 

posted @ 2025-11-05 14:27  ouyeye  阅读(13)  评论(0)    收藏  举报