数组和枚举 -- 写了四年代码, 刚刚才学会的新技巧

学习于: https://www.learncpp.com/cpp-tutorial/62-arrays-part-ii/

One of the big documentation problems with arrays is that integer indices do not provide any information to the programmer about the meaning of the index. Consider a class of 5 students:

数组的下标没有一种有意义的信息在里面, 看看下面的代码

const int numberOfStudents(5);
int testScores[numberOfStudents];
testScores[2] = 76;

Who is represented by testScores[2]? It’s not clear.

谁是testScore的第三个元素呢? 不知道!

This can be solved by setting up an enumeration where one enumerator maps to each of the possible array indices:

这个问题可以用枚举类型中的枚举量来映射每个数组下标来解决:

enum StudentNames
{
    KENNY, // 0
    KYLE, // 1
    STAN, // 2
    BUTTERS, // 3
    CARTMAN, // 4
    MAX_STUDENTS // 5
};
 
int main()
{
    int testScores[MAX_STUDENTS]; // allocate 5 integers
    testScores[STAN] = 76;
 
    return 0;
}

In this way, it’s much clearer what each of the array elements represents. Note that an extra enumerator named MAX_STUDENTS has been added. This enumerator is used during the array declaration to ensure the array has the proper length (as the array length should be one greater than the largest index). This is useful both for documentation purposes, and because the array will automatically be resized if another enumerator is added:

这样做的话, 数组的每个元素表示的就很清楚了. 注意在枚举类型的最后面有一个额外的枚举量, 这个枚举量用来给数组提供合适的大小, 因为数组的可访问元素下标总是等于数组长度-1. 这样做的话, 代码可读性就更高了, 而且,这个数组长度也会自动增长, 如果有一个新的枚举量加入的话:

enum StudentNames
{
    KENNY, // 0
    KYLE, // 1
    STAN, // 2
    BUTTERS, // 3
    CARTMAN, // 4
    WENDY, // 5
    MAX_STUDENTS // 6
};
 
int main()
{
    int testScores[MAX_STUDENTS]; // allocate 6 integers
    testScores[STAN] = 76; // still works
 
    return 0;
}

Note that this “trick” only works if you do not change the enumerator values manually!

注意: 这个技巧只有在你不手动改变枚举量的值的情况下才管用. 因为如果你随意交换了两个枚举量的值, 那么他们在数组中的指向也就发生了变化, 而在末尾添加新的数据是不会影响先前的数据的. 

 

总结: 这个技巧的适用范围还是很广的, 同样可以用于Java编程中

转载于:https://www.cnblogs.com/litran/p/10628855.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值