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

学习于: 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!

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

扫描二维码关注公众号,回复: 5716928 查看本文章

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

猜你喜欢

转载自www.cnblogs.com/litran/p/10628855.html