使用bitset::operator[]是否等同于使用bitset::test,还是有一些底层优化?
也就是说,这两个循环是否等价?
使用位集::operator[]:
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));
}
}使用bitset::test():
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));
}
}发布于 2011-08-20 11:45:13
来自C++03标准,§23.3.5.2/39-41:
bool test(size_t pos) const;
要求: pos有效
抛出:如果pos不对应于有效的位位置,则抛出 out_of_range。
返回:如果中pos位置的位的值为1,则返回true。
§23.3.5.2/46-48:
布尔运算符size_t pos const;
要求: pos有效。
抛出: nothing。
返回: test(pos)。
§23.3.5.2/49-51:
位集::引用运算符size_t pos;
要求: pos有效。
抛出: nothing。
返回:一个bitset<N>::reference类型的对象,使得(*this)[pos] == this- test(pos),并且使得(*this)[pos] = val等价于this->set(pos, val)。
因此,当对象为const时,它们返回相同的值,除了当pos无效时,test抛出out_of_range,而operator[]不抛出任何东西。当对象不是const时,操作符返回一个代理对象,允许修改对象的数据。
发布于 2011-08-20 11:47:27
与访问运算符([])不同,测试函数在检索位值之前对位置执行范围检查。如果位置不是有效的位位置,则抛出out_of_range。
您可以在以下位置找到参考资料:
http://www.cplusplus.com/reference/stl/bitset
发布于 2011-08-20 19:29:09
我会这样优化它:
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));
}
}
}类似地,另一个实现也是如此。
https://stackoverflow.com/questions/7129488
复制相似问题