复数 / 矩阵乘法手写库

template<typename CpType>
struct Cp { // Complex Structure
	CpType a, b;
	Cp() {}
	Cp(CpType _a, CpType _b) {a  = _a, b = _b; }
	Cp operator + (const Cp& tmp)const { return Cp(a + tmp.a, b + tmp.b); }
	Cp operator * (const Cp& tmp)const { return Cp(a * tmp.a - b * tmp.b, a * tmp.b + b * tmp.a); }
	Cp operator - (const Cp& tmp)const { return Cp(a - tmp.a, b - tmp.b); }
	Cp &operator += (const Cp& tmp) { *this = *this + tmp; return *this; }
	Cp &operator -= (const Cp& tmp) { *this = *this - tmp; return *this; }
	Cp &operator *= (const Cp& tmp) { *this = *this * tmp; return *this; }
	void makeI() { a = 1, b = 0; }
	bool isI() { return a == 1 && b == 0; }
};

#define Upper_size 2 // Here to Define the Size of Your Matrix
template<typename M_type>
struct Matrix { // Matrix Structure
	#define dor(i, a, b) for (int i = (a); i < (b); i ++ ) // Defined for(without upper size)
	#define all(i) for (int i = (0); i < (Upper_size); i ++ )
	M_type s[Upper_size][Upper_size];
	void clear() { memset(s, 0, sizeof s); }
	void makeI() { all(i) s[i][i] = 1; }
	Matrix operator + (const Matrix& tmp)const { 
		Matrix ans; ans.clear(); 
		all(i) all(j) ans.s[i][j] = s[i][j] + tmp.s[i][j]; return ans; 
	}
	Matrix operator - (const Matrix &tmp)const {
		Matrix ans; ans.clear();
		all(i) all(j) ans.s[i][j] = s[i][j] - tmp.s[i][j]; return ans;
	}
	Matrix operator * (const Matrix& tmp)const {
		Matrix ans; ans.clear();
		all(i) all(j) all(k) ans.s[i][j] += (s[i][k] * tmp.s[k][j]);
		return ans;
	}
	Matrix &operator += (const Matrix& tmp) { *this = *this + tmp; return *this; }
	Matrix &operator *= (const Matrix& tmp) { *this = *this * tmp; return *this; }
	Matrix &operator -= (const Matrix& tmp) { *this = *this - tmp; return *this; }
	void init(int tmp[][Upper_size]) {
		all(i) all(j) s[i][j] = tmp[i][j];
	}
};

int main() {
	// Usage Of Complex-Structure
	Cp<int> a(0, 1); Cp<int> b(1, 2);
	a *= b; printf("%d %d\n", a.a, b.b);
	
	Matrix<int> M_a, M_b; // <int> must be defined for the typename
	int tmpa[2][2] = {{1, 1}, {2, 2}};
	int tmpb[2][2] = {{2, 3}, {4, 5}};
	M_a.init(tmpa), M_b.init(tmpb);
	M_a *= M_b;
	for (int i = 0; i < 2; i ++ )
		for (int j = 0; j < 2; j ++ )
			printf("%d ", M_a.s[i][j]);
}

Matrix 库可以展开循环,init 的方式也可以改的更简单。仅供参考吧

posted @   Link-Cut-Y  阅读(49)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示