program tip

부울 값을 뒤집는 가장 쉬운 방법은 무엇입니까?

radiobox 2020. 8. 2. 18:04
반응형

부울 값을 뒤집는 가장 쉬운 방법은 무엇입니까?


나는 그것이 이미 무엇인지에 따라 부울을 뒤집기를 원합니다. 그것이 사실이라면-거짓으로 만드십시오. 그것이 거짓이라면-사실로 만드십시오.

내 코드 발췌는 다음과 같습니다.

switch(wParam) {

case VK_F11:
  if (flipVal == true) {
     flipVal = false;
  } else {
    flipVal = true;
  }
break;

case VK_F12:
  if (otherVal == true) {
     otherValVal = false;
  } else {
    otherVal = true;
  }
break;

default:
break;
}

다음과 같이 값을 뒤집을 수 있습니다.

myVal = !myVal;

따라서 코드는 다음과 같이 단축됩니다.

switch(wParam) {
    case VK_F11:
    flipVal = !flipVal;
    break;

    case VK_F12:
    otherVal = !otherVal;
    break;

    default:
    break;
}

분명히 당신은 공장 패턴이 필요합니다!

KeyFactory keyFactory = new KeyFactory();
KeyObj keyObj = keyFactory.getKeyObj(wParam);
keyObj.doStuff();


class VK_F11 extends KeyObj {
   boolean val;
   public void doStuff() {
      val = !val;
   }
}

class VK_F12 extends KeyObj {
   boolean val;
   public void doStuff() {
      val = !val;
   }
}

class KeyFactory {
   public KeyObj getKeyObj(int param) {
      switch(param) {
         case VK_F11:
            return new VK_F11();
         case VK_F12:
            return new VK_F12();
      }
      throw new KeyNotFoundException("Key " + param + " was not found!");
   }
}

:디

</sarcasm>

값이 0 또는 1 인 것을 알 수 있습니다 flipval ^= 1.


내가 찾은 가장 쉬운 솔루션 :

x ^= true;

정보를 위해-정수 대신 필수 필드가 더 큰 유형의 단일 비트 인 경우 'xor'연산자를 대신 사용하십시오.

int flags;

int flag_a = 0x01;
int flag_b = 0x02;
int flag_c = 0x04;

/* I want to flip 'flag_b' without touching 'flag_a' or 'flag_c' */
flags ^= flag_b;

/* I want to set 'flag_b' */
flags |= flag_b;

/* I want to clear (or 'reset') 'flag_b' */
flags &= ~flag_b;

/* I want to test 'flag_b' */
bool b_is_set = (flags & flag_b) != 0;

이것은 모두에게 무료로 보인다 ... Heh. 여기 또 다른 변형이 있는데, 이것은 내가 생산 코드에 권장하는 것보다 "영리한"범주에 더 있다고 생각합니다.

flipVal ^= (wParam == VK_F11);
otherVal ^= (wParam == VK_F12);

장점은 다음과 같습니다.

  • 아주 간결한
  • 분기가 필요하지 않습니다

그리고 명백한 단점은

  • 아주 간결한

This is close to @korona's solution using ?: but taken one (small) step further.


Just because my favorite odd ball way to toggle a bool is not listed...

bool x = true;
x = x == false;

works too. :)

(yes the x = !x; is clearer and easier to read)


The codegolf'ish solution would be more like:

flipVal = (wParam == VK_F11) ? !flipVal : flipVal;
otherVal = (wParam == VK_F12) ? !otherVal : otherVal;

I prefer John T's solution, but if you want to go all code-golfy, your statement logically reduces to this:

//if key is down, toggle the boolean, else leave it alone.
flipVal = ((wParam==VK_F11) && !flipVal) || (!(wParam==VK_F11) && flipVal);
if(wParam==VK_F11) Break;

//if key is down, toggle the boolean, else leave it alone.
otherVal = ((wParam==VK_F12) && !otherVal) || (!(wParam==VK_F12) && otherVal);
if(wParam==VK_F12) Break;

flipVal ^= 1;

same goes for

otherVal

Clearly you need a flexible solution that can support types masquerading as boolean. The following allows for that:

template<typename T>    bool Flip(const T& t);

You can then specialize this for different types that might pretend to be boolean. For example:

template<>  bool Flip<bool>(const bool& b)  { return !b; }
template<>  bool Flip<int>(const int& i)    { return !(i == 0); }

An example of using this construct:

if(Flip(false))  { printf("flipped false\n"); }
if(!Flip(true))  { printf("flipped true\n"); }

if(Flip(0))  { printf("flipped 0\n"); }
if(!Flip(1)) { printf("flipped 1\n"); }

No, I'm not serious.

참고URL : https://stackoverflow.com/questions/610916/easiest-way-to-flip-a-boolean-value

반응형