(如何)可以计数枚举中的项目? [英] (How) can I count the items in an enum?

查看:101
本文介绍了(如何)可以计数枚举中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有类似

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< Folders,ContainerClass *> 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.

这篇关于(如何)可以计数枚举中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆