我正在制作 vector<bool>
执行。我保存了一个 unsigned int 并使用按位运算得到一个 true 和 false 的 vector 。我的问题是这样的;我可以通过 operator[] 访问各个位,但是如何获得对这样一个位的引用以便我可以编写
Vector<bool> v(5, true);
v[3] = false;
我在某处听说您不应该对单个位进行引用/指针。用于检索位值的代码摘要:
...
unsigned int arr; // Store bits as unsigned int
unsigned int size_vec; // The size of "bool vector"
...
bool& Vector<bool>::operator[](unsigned int i) {
if (i>=vec_size || i<0) {
throw out_of_range("Vector<bool>::operator[]");
}
int index = 1 << (i-1);
bool n = false;
if (index & arr) {
n=true;
}
return n;
};
那么,您如何才能返回某种引用,从而使更改各个位成为可能?
最佳答案
您需要定义一个具有适当运算符重载的代理对象,以便它像bool&
一样工作。但地址个别位。这就是std::vector<bool>
像这样:
struct Bit
{
public:
typedef unsigned char byte;
Bit(byte& _byte, byte _bit)
: m_byte(_byte), m_mask(1u << _bit)
{}
operator bool() const
{
return m_byte & m_mask;
}
Bit& operator=(bool x)
{
m_byte = x ? m_byte | m_mask : m_byte & ~m_mask;
return *this;
}
private:
byte& m_byte;
const byte m_mask;
};
一般来说,我会建议避免像这样依赖于 C++ 中偷偷摸摸的隐式转换的事情,因为它真的会扰乱你的直觉,而且它不能很好地处理像 auto
这样的事情。和 decltype
在 C++11 中。
关于c++ - 如何使 operator[] 返回对 unsigned int 中各个位的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8566694/