gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:06:02 26 4
gpt4 key购买 nike

使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com