6

以我的经验,现实世界很少提供非负整数的索引。许多事情甚至没有用数字表示。并且许多具有数字表示索引的事物的索引不是从 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 的整个转换是一整层的复杂性,这似乎是不必要的。

有人可以解释一下枚举索引是否有效,并列出每种方法的优缺点吗?如果存在这样的信息,为什么 C 标准中缺少一个看似有用的特性?

4

2 回答 2

3

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

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

std::map<Weekday,int> hoursWorkedPerDay;
于 2012-11-06T18:49:09.563 回答
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)是未定义的行为

于 2012-11-06T18:49:07.760 回答