2011-08-20 75 views
1

使用bitset :: operator []等價於使用bitset :: test還是存在一些基礎優化?bitset :: operator [] == false/true或bitset :: test?

也就是說,這兩個循環等價嗎?

使用位集::操作符[]:

static const int UP = 0; 
static const int DOWN = 1; 

for(int i = 1; i < KEY_MAX; ++i) { 
    if(_handler && (_prevKey[i] == UP && _curKey[i] == DOWN)) { 
     _handler->EnqueueEvent(new KeyboardKeyDownEvent(i)); 
    } 
    if(_handler && (_prevKey[i] == DOWN && _curKey[i] == DOWN)) { 
     _handler->EnqueueEvent(new KeyboardKeyPressEvent(i)); 
    } 
    if(_handler && (_prevKey[i] == DOWN && _curKey[i] == UP)) { 
     _handler->EnqueueEvent(new KeyboardKeyUpEvent(i)); 
    } 
} 

使用位集::測試():

static const bool UP = false; 
static const bool DOWN = true; 

for(int i = 1; i < KEY_MAX; ++i) { 
    if(_handler && (_prevKey.test(i) == UP && _curKey.test(i) == DOWN)) { 
     _handler->EnqueueEvent(new KeyboardKeyDownEvent(i)); 
    } 
    if(_handler && (_prevKey.test(i) == DOWN && _curKey.test(i) == DOWN)) { 
     _handler->EnqueueEvent(new KeyboardKeyPressEvent(i)); 
    } 
    if(_handler && (_prevKey.test(i) == DOWN && _curKey.test(i) == UP)) { 
     _handler->EnqueueEvent(new KeyboardKeyUpEvent(i)); 
    } 
} 

回答

3

從C++ 03標準,§23.3.5.2/ 39-41 :

bool test(size_t pos) const; 

要求:pos有效
拋出:out_of_range如果pos不對應於有效位的位置。
返回:true如果位於*this的位置pos的位值爲1。

§23.3.5.2/ 46-48:

bool operator[](size_t pos) const; 

要求:pos是有效的。
拋出:沒有。
返回:test(pos)

§23.3.5.2/ 49-51:

bitset<N>::reference operator[](size_t pos); 

要求:pos是有效的。
拋出:沒有。
返回:bitset<N>::reference類型的對象,使(*this)[pos] == this- test(pos),並使(*this)[pos] = val相當於this->set(pos, val)

所以當對象是const,他們返回相同的值,除此之外,當pos無效test拋出out_of_rangeoperator[]拋出什麼。當對象是而不是const時,運算符返回一個代理對象,允許對象更改對象的數據。

0

與訪問運算符([])不同,測試函數在檢索位值之前對位置執行範圍檢查。如果位置不是有效位位置,則會拋出out_of_range。

你可以找到參考資料:

http://www.cplusplus.com/reference/stl/bitset

0

我將優化這樣說:

int nPrevKey, nCurKey; 

for(int i = 1; i < KEY_MAX; ++i) 
{ 
    if(_handler) 
    { 
     nPrevKey = _prevKey[i]; 
     nCurKey = _curKey[i]; 

     if(nPrevKey == UP && nCurKey == DOWN) 
     { 
      _handler->EnqueueEvent(new KeyboardKeyDownEvent(i)); 
     } 
     if(nPrevKey == DOWN && nCurKey == DOWN) 
     { 
      _handler->EnqueueEvent(new KeyboardKeyPressEvent(i)); 
     } 
     if(nPrevKey == DOWN && nCurKey == UP) 
     { 
      _handler->EnqueueEvent(new KeyboardKeyUpEvent(i)); 
     } 
    } 
} 

並且類似地,其他實現。