[刷题]算法竞赛入门经典/第五章/代码对齐(习题5-1)

将我们从terminal cin的各行代码,assume成一个2d matrix,用row和col分别记录最大列数,最大行数(as follows : row=4,col=5)

    start:         integer;       //           begins     here
stop:   integer;//         ends  here  
      s:   string;      
  c:   char;   //temp 
Input format is:?(Note:Terminate with '#' input)
-------------------------------------------------
  start:  integer;    // begins here
stop: integer; //  ends here  
 s:  string;   
c:   char; // temp
#
-------------------------------------------------
Input format is:?
-------------------------------------------------
start: integer; // begins here
stop:  integer; // ends   here
s:     string;
c:     char;    // temp
-------------------------------------------------

  

 

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>

using namespace std;
const int maxn = 1010;
// 如果申明的是全局/静态数组,系统会把数组的内容自动初始化为0。
int each_col_max_len[maxn];//用一个数组记录,每个列最长元素长度
vector<string> words[maxn];

void print(const string &s, int len, char extra){
    cout << s;
    for (int i = 0; i < len-s.length()+1; ++i) {
        cout << extra;
    }
}
int main(){
    int row=0,col=0;
    string s ,x;

    while (getline(cin,s)) {
//        if (s[0] == '#') break;//提交时记得注释掉这一行
        stringstream ss(s);
        while (ss >> x) words[row].push_back(x);//往里边输入的时候最好用x,好理解
        col = max(col,(int)words[row].size());//返回想象成矩阵,最大列数
        row++;
    }

    for (int i = 0; i < row ; ++i) {
        for (int j = 0; j < words[i].size(); ++j) {
            //用一个数组记录,每个列最长元素长度
            each_col_max_len[j] = max(each_col_max_len[j], (int)words[i][j].length());
        }
    }

    for (int i = 0; i < row ; ++i) {
        for (int j = 0; j < words[i].size(); ++j) {
            if (j == (int)words[i].size() - 1) cout << words[i][j];//某一行最后一列,直接输出
            else print(words[i][j],each_col_max_len[j],' ');
        }
        cout << endl;
    }
    return 0;
}



 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值