C++ 枚举中的最大值和最小值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/159006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:20:39  来源:igfitidea点击:

Max and min values in a C++ enum

c++enums

提问by Matt

Is there a way to find the maximum and minimum defined values of an enum in c++?

有没有办法在 c++ 中找到枚举的最大和最小定义值?

回答by Jeff Yates

No, there is no way to find the maximum and minimum defined values of any enum in C++. When this kind of information is needed, it is often good practice to define a Last and First value. For example,

不,没有办法在 C++ 中找到任何枚举的最大值和最小值。当需要此类信息时,定义 Last 和 First 值通常是一种很好的做法。例如,

enum MyPretendEnum
{
   Apples,
   Oranges,
   Pears,
   Bananas,
   First = Apples,
   Last = Bananas
};

There do not need to be named values for every value between Firstand Last.

First和之间的每个值不需要命名值Last

回答by dalle

No, not in standard C++. You could do it manually:

不,不是在标准 C++ 中。你可以手动完成:

enum Name
{
   val0,
   val1,
   val2,
   num_values
};

num_valueswill contain the number of values in the enum.

num_values将包含枚举中的值数。

回答by Justsalt

No. An enum in C or C++ is simply a list of constants. There is no higher structure that would hold such information.

不。 C 或 C++ 中的枚举只是一个常量列表。没有更高的结构可以保存此类信息。

Usually when I need this kind of information I include in the enum a max and min value something like this:

通常当我需要这种信息时,我会在枚举中包含一个最大值和最小值,如下所示:

enum {
  eAaa = 1,
  eBbb,
  eCccc,
  eMin = eAaaa,
  eMax = eCccc
}

See this web page for some examples of how this can be useful: Stupid Enum Tricks

有关这如何有用的一些示例,请参阅此网页:Stupid Enum Tricks

回答by Tiendil

  enum My_enum
    {
       FIRST_VALUE = 0,

       MY_VALUE1,
       MY_VALUE2,
       ...
       MY_VALUEN,

       LAST_VALUE
    };

after definition, My_enum::LAST_VALUE== N+1

定义后,My_enum::LAST_VALUE== N+1

回答by wannes

Not automatically, but you can add artificial enum values to signify min and max values, e.g.

不是自动的,但您可以添加人工枚举值来表示最小值和最大值,例如

typedef enum {start_of_colors=-1, eRed, eWhite, eBlue, eGray,
end_of_colors} eListOfTags;

for (eListOfTags i = start_of_colors+1; i < end_of_colors; i++) {
.... 
}

回答by Wael

you don't even need them, what I do is just I say for example if you have:

你甚至不需要它们,我所做的只是我说,例如,如果你有:

enum Name{val0,val1,val2};

if you have switch statement and to check if the last value was reached do as the following:

如果您有 switch 语句并检查是否达到了最后一个值,请执行以下操作:

if(selectedOption>=val0 && selectedOption<=val2){

   //code
}