使用 bitset::operator[] 等同于使用 bitset::test 还是有一些底层优化?
也就是说,这两个循环是等价的吗?
使用 bitset::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));
}
}
使用位集::测试():
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));
}
}
最佳答案
来自 C++03 标准,§23.3.5.2/39-41:
bool test(size_t pos) const;
Requires:
pos
is valid
Throws:out_of_range
ifpos
does not correspond to a valid bit position.
Returns:true
if the bit at positionpos
in*this
has the value one.
§23.3.5.2/46-48:
bool operator[](size_t pos) const;
Requires:
pos
is valid.
Throws: nothing.
Returns:test(pos)
.
§23.3.5.2/49-51:
bitset<N>::reference operator[](size_t pos);
Requires:
pos
is valid.
Throws: nothing.
Returns: An object of typebitset<N>::reference
such that(*this)[pos] == this- test(pos)
, and such that(*this)[pos] = val
is equivalent tothis->set(pos, val)
.
所以当对象是const
,它们返回相同的值,除了当 pos
时无效 test
抛出 out_of_range
同时operator[]
什么都不扔。当对象不是时const
,运算符返回一个代理对象,允许改变对象的数据。
关于c++ - bitset::operator[] == false/true 还是 bitset::test?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7129488/