Skip to content

遵从不易出错的代码风格

案例1 EmbraceDSA中的示例代码

我们为这段示例代码,展示更好的风格与更差的风格。

// How to improve the style of this program?

#include <cstdio>

int matrix[2000][2000];

int main() {
    int n, m, q;
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
            scanf("%d", &matrix[i][j]);
        }
    }
    scanf("%d", &q);
    int sum = 0;
    for (int i = 1; i <= q; ++i) {
        int x, y, a, b;
        scanf("%d %d %d %d", &x, &y, &a, &b);
        for (int j = 0; j < a; ++j) {
            for (int k = 0; k < b; ++k) {
                sum += matrix[x + j][y + k];
            }
        }
        printf("%d\n", sum);
    }
    return 0;
}

下面给出正面例子和反面例子.

//generated by ChatGLM

#include <cstdio>

// 定义矩阵的最大尺寸
const int MAX_SIZE = 2000;
int matrix[MAX_SIZE][MAX_SIZE];

// 函数声明
void readMatrix(int rows, int cols);
void processQueries(int num_queries, int rows, int cols);
int calculateSubmatrixSum(int start_row, int start_col, int submatrix_rows, int submatrix_cols);

int main() {
    int rows, cols, num_queries;

    // 读取矩阵的行数和列数
    scanf("%d %d", &rows, &cols);

    // 读取矩阵数据
    readMatrix(rows, cols);

    // 读取查询的数量
    scanf("%d", &num_queries);

    // 处理每个查询
    processQueries(num_queries, rows, cols);

    return 0;
}

// 读取矩阵数据
void readMatrix(int rows, int cols) {
    for (int row = 0; row < rows; ++row) {
        for (int col = 0; col < cols; ++col) {
            scanf("%d", &matrix[row][col]);
        }
    }
}

// 处理所有查询
void processQueries(int num_queries, int rows, int cols) {
    for (int query = 0; query < num_queries; ++query) {
        int start_row, start_col, submatrix_rows, submatrix_cols;

        // 读取查询中的起始行、起始列、子矩阵的行数和列数
        scanf("%d %d %d %d", &start_row, &start_col, &submatrix_rows, &submatrix_cols);

        // 计算并输出子矩阵元素的和
        printf("%d\n", calculateSubmatrixSum(start_row, start_col, submatrix_rows, submatrix_cols));
    }
}

// 计算子矩阵元素的和
int calculateSubmatrixSum(int start_row, int start_col, int submatrix_rows, int submatrix_cols) {
    int submatrix_sum = 0;
    for (int sub_row = 0; sub_row < submatrix_rows; ++sub_row) {
        for (int sub_col = 0; sub_col < submatrix_cols; ++sub_col) {
            submatrix_sum += matrix[start_row + sub_row][start_col + sub_col];
        }
    }
    return submatrix_sum;
}
// a condense collection of anti-patterns
#include <cstdio>
#define S scanf
#define P printf
#define F for
int A[2000][2000],n,m,q,i,a,b,s;
int main(){
    // warning: DO NOT write your code this way
    F(S("%d%d",&n,&m),i=1;i<=n;++i)
        F(a=1;a<=m;S("%d",&A[i][a++])); 

    F(S("%d",&q);q--;P("%d\n",s))     
        F(S("%d%d%d%d",&n,&m,&a,&b),s=0;--a>=0;) 
            F(i=0;i<b;s+=A[n+a][m+(i++)]);
}

案例2 一道展示代码风格的算法竞赛题目

//https://www.luogu.com.cn/problem/P9754
#include<iostream>
#include<vector>
#include<map>
#include<string>
using namespace std;
// 1. map struct name to struct layout 
// 2. map variable name to variable offset
// 3. All "elements" become a special struct
long long align_it(long long size, long long align){
    if(size%align!=0){
        return size + (align - size%align);
    }else{
        return size;
    }
}
struct Member{
    string name;
    string type;
    long long start_offset;
    long long size;
    long long align;
    Member(){start_offset = size = align = 0;}
};
struct Layout{
    vector<Member> members;
    long long unaligned_size; // used when append members
    long long aligned_size; // used when this struct is a member of another struct
    long long align;
    Layout(){unaligned_size = aligned_size = align = 0;}
    Layout(long long _size, long long _align){
        unaligned_size = _size;
        align = _align;
        aligned_size = align_it(unaligned_size, align);
    }
    void append(Member m, int out){ // 
        align = max(align, m.align);
        m.start_offset = align_it(unaligned_size, m.align);
        unaligned_size = m.start_offset + m.size;
        aligned_size = align_it(unaligned_size, align);
        members.push_back(m);
        if(out){
            cout << m.start_offset << endl;
        }
    }
    Member find_member_by_name(string n){
        for(auto x: members){
            if(x.name == n) return x;
        }
    }
    Member find_member_by_offset(long long offset){
        for(auto x:members){
            if(x.start_offset <= offset && x.start_offset+ x.size >offset)return x;
        }
        Member m;
        m.start_offset = -1;
        return m;
    }
};
map<string, Layout> structs;

void initialize(){
    structs["byte"] = Layout(1, 1);
    structs["short"] = Layout(2, 2);
    structs["int"] = Layout(4, 4);
    structs["long"] = Layout(8, 8);
}
Member read_member(){
    Member m;
    cin >> m.type >> m.name;
    m.size = structs[m.type].aligned_size;
    m.align = structs[m.type].align;
    return m;
}
char buffer[1005];
void access_member(){
    string s; cin >> s;
    int L = s.length();
    string cur_type = "ELEM"; 
    long long cur_start = 0;
    for(int i=0, last = 0, j = 0;i<=L;++i){
        if(i==L || s[i]=='.'){
            //access buffer[0,j] //L[last,i-1];
            buffer[j] = '\0';
            string name(buffer);
            Member m = structs[cur_type].find_member_by_name(name);
            cur_start = cur_start + m.start_offset;
            cur_type = m.type;
            last = i+1; j = 0;
        }else{
            buffer[j] = s[i];
            ++j;
        }
    }
    cout << cur_start << endl;
}
bool basic(string t){
    return t == "byte" || t == "short" || t == "int" || t == "long";
}
void access_address(){
    long long offset;
    cin >> offset;
    string cur_type = "ELEM";
    long long cur_start = 0;
    string ans;
    bool first = true;
    while(true){
        Member m = structs[cur_type].find_member_by_offset(offset);
        if(m.start_offset==-1){
            cout << "ERR" <<endl; return;
        }
        offset -= m.start_offset;
        if(first){
            first = false;
        }else{
            ans.append(".");
        }
        cur_type = m.type;
        ans.append(m.name);
       // cout << offset << " " << m.name <<" "<< m.type << endl;
        if(basic(m.type)){
            cout << ans << endl;
            return;
        }
    }
}
int main(){
    initialize();
    int n;
    cin >> n;
    int op;
    structs["ELEM"] = Layout();
    for(int i=0;i<n;++i){
        cin >> op;
        if(op==1){
            string s; int k;
            cin >> s >> k;
            structs[s] = Layout();
            for(int j=0;j<k;++j){
                structs[s].append(read_member(),0);
            }
            cout <<structs[s].aligned_size <<" "<<structs[s].align <<endl;
        }else if(op==2){
            structs["ELEM"].append(read_member(),1);
        }else if(op==3){
            access_member();
        }else if(op==4){
            access_address();
        }
    }
    return 0;
}