稀疏矩阵的C++实现

本文介绍了如何使用C++实现稀疏矩阵,包括构造、赋值、转置、加法和乘法操作。通过使用map数据结构存储非零元素,提高了空间效率。并提供了完整的测试代码示例。
摘要由CSDN通过智能技术生成
 实现部分:
include <iostream>
#include <iomanip>
#include <map>
using namespace std;
class matrix{
	friend ostream &operator<<(ostream &,matrix&);
private:
	int row, column, num;
	map<int, map<int, int>> m;  //行号→(列号,值)
public:
	matrix() = default;
	matrix(int r, int c, int n) :row(r), column(c), num(n) {}
	matrix &operator=(const matrix &right)
	{
		row = right.row;
		column = right.column;
		num = right.num;
		m = right.m;
	}
	void add(int r, int c, int val){ m[r].emplace(c, val); }
	int Row() const { return row; }
	int Column() const { return column; }
	matrix transpose() const
	{
		matrix temp(column, row, num);
		for (auto it = m.begin(); it != m.end(); ++it)  //这一行的元素
		{
			const map<int, int> &elems = it->second;
			for (auto it2 = elems.begin(); it2 != elems.end(); ++it
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值