c++ - bitset::operator[] == false/true 还是 bitset::test?

标签 c++ bitset

使用 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 if pos does not correspond to a valid bit position.
Returns: true if the bit at position pos 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 type bitset<N>::reference such that (*this)[pos] == this- test(pos), and such that (*this)[pos] = val is equivalent to this->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/

相关文章:

c++ - 更好地提升 asio deadline_timer 示例

C++在构造函数中选择类成员的模板类型

c++ - 使用 VS2010 在 C++ 中的位集

c++ - 从位集中读取位值并传输到字节数组

c++ - 类的位宽

c++ - Catch Lib 问题 - 匿名 namespace 重新定义。怎么解决

c++ - 新的 boost::thread 导致对象析构函数被调用的次数超过预期?

c++ - 在 C++ 类中设置我的窗口

c++ - 尝试翻转 std::bitset 中的位顺序

java - BitSet 在 List、Set 上的用例