c++ - 如何使 operator[] 返回对 unsigned int 中各个位的引用?

标签 c++ vector reference bit-manipulation operator-keyword

我正在制作 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/

相关文章:

c++ - 使用对象访问私有(private)成员

c++ - 查找 vector C++ 的唯一元素

c++ - std vector 保存指针和变量地址。清理?

java - Java 中的 ArrayList 和更多原始类型一起使用

c - C 中的动态数组 vector

C++ 对命名空间 Visual Studio Code 的 undefined reference

c++ - 为什么这个makefile在 'make clean'上执行一个目标

c++ - 从 C/C++ 代码执行 RDMSR 和 WRMSR 指令

sql - 通过id查看表

javascript - this.object.property = object.property 是通过引用或值传递的 Javascript;破坏垃圾收集器/内存泄漏