[关闭]
@Moritz 2019-03-26T04:23:39.000000Z 字数 1001 阅读 411

第六章 数据结构基础

aoapc_2nd C++ 所有文稿


6.1 再谈栈和队列

看不懂就背吧 结构体构造函数

  1. struct Point{
  2. int x,y;
  3. Point(int x=0,int y=0):x(x),y(y){}
  4. }

声明Point a,b(1,2)时分别调用了Point()Point(1,2)

例题 6-3 矩阵链乘

例题代码运用了结构体

  1. struct Matrix{
  2. int a,b;
  3. Matrix(int a=0,int b=0):a(a),b(a){}
  4. }m[26];
  5. for(int i=0;i<n;i++){
  6. cin>>str;
  7. int k=name[0]-'A';
  8. cin>>m.[k].a>>m[k].b;
  9. }

自己的代码则用pair来表示矩阵的行数和列数,用set存储矩阵

  1. int n;
  2. string str;
  3. stack<char> cacu;
  4. map<char,pair<int,int> > ma;
  5. cin>>n;
  6. for(int i=0; i<n; i++){
  7. char x;
  8. int a,b;
  9. cin>>x>>a>>b;
  10. ma[x]=make_pair(a,b);
  11. }
  12. while(cin>>str){
  13. bool flag=true;
  14. int row=0,col=0;
  15. long int tot=0,mul=1;
  16. for(int i=0; i<str.length(); i++) {
  17. cout<<"i="<<i<<endl;
  18. if (str[i]==')'){
  19. if (row==0&&col==0) {
  20. row=ma[cacu.top()].first;
  21. col=ma[cacu.top()].second;
  22. printf("row=%d col=%d mul=%d\n",row,col,mul);
  23. cacu.pop();
  24. }
  25. if (ma[cacu.top()].second!=row){
  26. flag=false;
  27. break;
  28. }
  29. mul=ma[cacu.top()].first*row*col;
  30. row=ma[cacu.top()].first;
  31. cacu.pop();//弹出矩阵
  32. cacu.pop();//弹出(
  33. tot+=mul;
  34. }
  35. else cacu.push(str[i]);
  36. printf("row=%d col=%d\n",row,col);
  37. }
  38. if(flag) cout<<tot<<endl;
  39. else cout<<"error"<<endl;
  40. }

6.2 链表

在数组中频繁移动元素是很低效的,如果可能,可以用链表替代。


2019.3.2

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注