Algorithm icon indicating copy to clipboard operation
Algorithm copied to clipboard

观摩学习代码,然后尝试在您的基础上把代码改得更易懂(从个人层面)

Open asukaminato0721 opened this issue 6 years ago • 2 comments

UVa1593

#pragma GCC optimize(3, "Ofast", "inline")
#include <bits/stdc++.h>
using namespace std;
vector<vector<string>> input;
vector<string> each;
size_t length[1010] = {0};
string line, word;
int main()
{
    while (getline(cin, line))
    {
        stringstream ss(line);
        each.clear();
        while (ss >> word)
        {
            each.push_back(word);
        }
        input.push_back(each);
    }
    for (auto &&i : input) //然后统计出每列 string 的最大宽度
    {
        for (size_t j = 0; j < i.size(); j++)
        {
            length[j] = max(length[j], i[j].size());
        }
    }
    for (auto &&i : input) // 根据每列 max 输出
    {
        for (size_t j = 0; j < i.size() - 1; j++)
        {
            cout << i[j] << string(length[j] - i[j].size() + 1, ' ');
        }
        cout << i.back() << "\n";
    }
    return 0;
}

本代码我特意把 3 次循环展开写了,然后用 auto && 写法,可以让遍历更清楚。 C++11 没有 zip,所以第 2, 3 次循环不得已用了下标,好在不太影响可读性。至于为何不在循环体里 ++ 迭代器,因为那样会混杂(赋值和下标),影响理解。

asukaminato0721 avatar Sep 18 '20 14:09 asukaminato0721

有个很有用的宏

#define all(x) x.begin(),x.end()

asukaminato0721 avatar Sep 19 '20 08:09 asukaminato0721

确实能让代码变得更简洁,手动点赞!

wyjoutstanding avatar Sep 19 '20 08:09 wyjoutstanding