(如何)我可以计算枚举中的项目吗?

2021-12-30 00:00:00 count enumeration c++

当我有类似的事情时,我想到了这个问题

This question came to my mind, when I had something like

enum Folders {FA, FB, FC};

并想为每个文件夹创建一个容器数组:

and wanted to create an array of containers for each folder:

ContainerClass*m_containers[3];
....
m_containers[FA] = ...; // etc.

(使用地图更优雅:std::map m_containers;)

但是回到我最初的问题:如果我不想对数组大小进行硬编码怎么办,有没有办法计算出文件夹中有多少项目?(不依赖于例如 FC 是列表中的最后一项,如果我没记错的话,它会允许类似 ContainerClass*m_containers[FC+1] 的内容.)>

But to come back to my original question: What if I do not want to hard-code the array size, is there a way to figure out how many items are in Folders? (Without relying on e.g. FC being the last item in the list which would allow something like ContainerClass*m_containers[FC+1] if I'm not mistaken.)

推荐答案

没有什么好的方法可以做到这一点,通常你会在枚举中看到一个额外的项目,即

There's not really a good way to do this, usually you see an extra item in the enum, i.e.

enum foobar {foo, bar, baz, quz, FOOBAR_NR_ITEMS};

那么你可以这样做:

int fuz[FOOBAR_NR_ITEMS];

不过还是不太好.

当然,您确实意识到仅枚举中的项目数量是不安全的,例如

But of course you do realize that just the number of items in an enum is not safe, given e.g.

enum foobar {foo, bar = 5, baz, quz = 20};

项目数为 4,但枚举值的整数值将超出数组索引范围.使用枚举值进行数组索引并不安全,您应该考虑其他选项.

the number of items would be 4, but the integer values of the enum values would be way out of the array index range. Using enum values for array indexing is not safe, you should consider other options.

根据要求,使特殊条目更加突出.

edit: as requested, made the special entry stick out more.

相关文章