5

こんにちは、私は以下のコードを持っています:

enum {a, b, c, d, ..., z} abc;

int main()
{
  int val = 20;
  if (val == a || val == b ||val == c||val == d..... || val == z)
  {
    /*Do something*/
  }
}

OR何千もの列挙メンバーがある場合、すべてのメンバーをチェックする方法を先に進めることができるため、操作をスキップできる他の方法はありますか? 助けてください。

4

4 に答える 4

5

A modern compiler should just be able to optimize such code if, as in your case, the value of the expression is known at compile time. For readability and error checking I think that using a switch would be better:

switch (val)  {
 case a:;
 case b:;
 ....
 // your code goes here
}

As said, performance wise there shouldn't be much difference, the compiler will transform this to a table lookup (or other clever things) if appropriate or completely optimize it out if val is known at compile time.

But you can have the advantage of error checking compilers, here. If you don't have a default case, most compilers will warn you if you omit one of the enumeration constants. Also I think that this is clearer, since it doesn't repeat the evaluation of val all over the place.

于 2012-10-17T07:56:24.967 に答える
1

他の(より速い)解決策は次のとおりです

bool isInenum (int val)
{
    bool retVal = false
        switch(val)

    {
        case a:
        case b:
        case c:
        case d:
            {
                retVal = true;
            }

    }
    return retVal;
}
于 2012-10-17T20:34:13.397 に答える
0

C++ でマップを使用できます。==マップを使用すると、多数のとを使用せずにコンパクトなテストを作成できます||

しかし、最初にマップを初期化する必要があります。この初期化を任意の列挙型に対してコンパクトな方法で実行できるかどうかはわかりません。

#include <iostream>
#include <map>

using namespace std;

enum abc { a = 1, b = -1, c = 3, d = 0 };

int main()
{
  map<int, int> m;
  m[a] = m[b] = m[c] = m[d] = 1;
  cout << "b is " << ((m.find(b) == m.end()) ? "NOT " : "") << "in m" << endl;
  cout << "3 is " << ((m.find(3) == m.end()) ? "NOT " : "") << "in m" << endl;
  cout << "10 is " << ((m.find(10) == m.end()) ? "NOT " : "") << "in m" << endl;
  return 0;
}

出力 ( ideone ):

b is in m
3 is in m
10 is NOT in m
于 2012-10-17T07:34:36.777 に答える
0

列挙子の値は順番に割り当てられるため、次のような if ステートメントを配置するだけで十分です。

if(val<=z)

于 2012-10-17T06:57:43.890 に答える