首页 > 代码库 > 矩阵链乘
矩阵链乘
矩阵链乘之结构体构造函数
struct构造函数,和构造函数的重载函数长这个样子,和C++的构造函数差不过。
struct Dog { Dog() { name = "wangwang"; age = 10; } string name; int age;};
struct Dog { Dog() { name = "Ao di"; age = 2; } Dog(string n) { name = n; age = 10; } Car(string n, int c) { name = n; age = c; } string name; int age;};
下面这个厉害了:
struct Dog { Dog(string n = "Lihao", int c = 10) : name(n), age(c) {} //name = n, age = c string name; int age;};
这种构造函数非常好用。如果你只是想初始化一些变量。
结合uva442的AC代码,看看这种用法。
#include<iostream>#include<cstdio>#include<cstring>#include<stack>#include<string>using namespace std;#define maxn 30struct matrix{ int a, b; matrix(int a=0, int b=0) :a(a), b(b){} //神奇的构造函数。}mat[maxn];int main(){ int m; cin >> m; for (int i = 0; i < m; i++){ char name; cin >> name; cin >> mat[name - ‘A‘].a >> mat[name - ‘A‘].b; } char exp[200]; stack<matrix> s; while (cin >> exp){ int len = strlen(exp); bool error = false; int ans = 0; for (int i = 0; i < len; i++){ if (exp[i] >= ‘A‘&&exp[i] < ‘Z‘) s.push(mat[exp[i] - ‘A‘]); else if (exp[i] == ‘)‘){ matrix m1 = s.top(); s.pop(); matrix m2 = s.top(); s.pop(); if (m2.b != m1.a) { error = true; break; } ans += m2.a*m1.a*m1.b; s.push(matrix(m2.a, m1.b));//初始化之后,系统会生成一个指向该结构体的地址。 } } if (error) cout << "error" << endl; else cout << ans << endl; } return 0;}
矩阵链乘
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。