是否有一种替换C风格的Bool数组的标准方法

Is there a standard way to replace a C-style bool array?

本文关键字:风格 Bool 数组 方法 标准 替换 一种 是否      更新时间:2023-10-16

在这段代码中

void legacyFunction(int length, bool *bitset)
{
    // stuff, lots of stuff
}
int main()
{
    int somenumber = 6;
    // somenumber is set to some value here
    bool *isBitXSet = new bool[somenumber];
    // initialisation of isBitXSet.
    legacyFunction(somenumber, isBitXSet);
    delete[] isBitXSet;
    return 0;
}

我想用

之类的东西替换bool *isBitXSet = new bool[somenumber];
std::vector<bool> isBitXset(somenumber, false);

,但我不能做

legacyFunction(somenumber, isBitXSet.data());

因为data()不存在std::vector<bool>。而且我无法更改legacyFunction()的接口。

是否有c风格的布尔数组的替代方法?

您可以使用std::unique_ptr<T[]>std::make_unique

int main()
{
    int somenumber = 6;
    // somenumber is set to some value here
    auto isBitXSet = std::make_unique<bool[]>(somenumber);    
    // initialisation of isBitXSet.
    legacyFunction(somenumber, isBitXSet.get());
    return 0;
}

另外,您可以通过创建自己的bool包装器来"欺骗" std::vector

struct my_bool { bool _b; };
std::vector<my_bool> v; // will not use `vector<bool>` specialization

如果您在编译时知道阵列的大小,请考虑使用std::array