C - Enum-Indexed Arrays的优点/缺点

时间:2012-11-06 18:41:19

标签: c++ c arrays enums indexing

根据我的经验,现实世界很少提供非负整数的索引。许多事情甚至没有用数字表示。许多具有数字表示索引的东西不会将其索引开始为0.为什么我们仍然只限于整数索引数组?

也许我错了,但似乎枚举索引数组通常比数字索引数组更合适(因为枚举通常更准确,“真实世界”表示)。虽然枚举通常可以相对容易地转换为C风格的数组索引......

enum Weekday = {
    SUNDAY,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY
}

// hopefully C doesn't allow nonsequential enum values; else pray to God
// no one does something like setting Sunday = 4 and Saturday = 4096
int numberOfDays = Saturday-Sunday+1;

int hoursWorkedPerDay[numberOfDays];

hoursWorkedPerDay[(int)SUNDAY] = 0;
hoursWorkedPerDay[(int)MONDAY] = 8;
hoursWorkedPerDay[(int)TUESDAY] = 10;
hoursWorkedPerDay[(int)WEDNESDAY] = 6;
hoursWorkedPerDay[(int)THURSDAY] = 8;
hoursWorkedPerDay[(int)FRIDAY] = 8;
hoursWorkedPerDay[(int)SATURDAY] = 0;

...我们仍然需要保持枚举数和数组大小之间的一致性(但是,这不是一个糟糕的解决方案,因为“SUNDAY”没有比0更有效的整数映射),更重要的是,任何可以转换为int的东西仍然可以放入索引来操作数组:

// continued from above
void resetHours (void) {
    int i = 0;
    int hours = 0;
    for (i = 0; i<numberOfDays; i++) {
        hoursWorkedPerDay[hours] = i;
        // oops, should have been: "...[i] = hours;"
        // an enum-indexed implementation would have caught this
        // during compilation
    }
}

此外,从enum到int的整个转换是整个复杂层,似乎是不必要的。

有人可以解释一下enum-indices是否有效,并列出每种方法的优缺点?也许为什么C标准中缺少一个看似有用的功能,如果存在这样的信息?

2 个答案:

答案 0 :(得分:3)

如果你真的想使用枚举作为索引,你应该明确声明整数值。

另一方面,我个人更喜欢s.th.类型安全(即没有丑陋的演员,甚至可能没有必要),如:

std::map<Weekday,int> hoursWorkedPerDay;

答案 1 :(得分:2)

Sunday =0 //by default, if you won't mention explicit value then it would take 0

Saturday = 6 // as in your example

所以

int numberOfDays = Saturday-Sunday; // which is 6 

int hoursWorkedPerDay[numberOfDays]; 

数组只有6个位置来保存该值。

hoursWorkedPerDay[(int)SUNDAY] = 0;
hoursWorkedPerDay[(int)MONDAY] = 8;
hoursWorkedPerDay[(int)TUESDAY] = 10;
hoursWorkedPerDay[(int)WEDNESDAY] = 6;
hoursWorkedPerDay[(int)THURSDAY] = 8;
hoursWorkedPerDay[(int)FRIDAY] = 8;
hoursWorkedPerDay[(int)SATURDAY] = 0;  

访问数组索引(为6)是未定义的行为