根据我的经验,现实世界很少提供非负整数的索引。很多东西甚至不是用数字来表示的。并且许多具有数字表示的索引的事物的索引不是从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;...we仍然需要维护枚举数量和数组大小之间的一致性(然而,这并不是一个糟糕的解决方案,因为对于"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
}
}此外,从枚举到int的整个转换是一个看起来不必要的整个复杂性层。
有人能解释一下枚举索引是否有效,并列出每种方法的优缺点吗?如果存在这样的信息,为什么在C标准中缺少一个看起来如此有用的特性?
发布于 2012-11-07 02:49:10
如果你真的想使用枚举作为索引,你应该显式声明整数值。
另一方面,我个人更喜欢s.th。类型安全(即没有丑陋的类型转换,这甚至可能不是必需的),例如:
std::map<Weekday,int> hoursWorkedPerDay;发布于 2012-11-07 02:49:08
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)的访问是未定义的行为
https://stackoverflow.com/questions/13257260
复制相似问题