有没有标准的方法来替换C风格的bool阵列?

Tob*_*obi 4 c++ arrays boolean std

在这段代码中

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;
}
Run Code Online (Sandbox Code Playgroud)

我想用类似bool *isBitXSet = new bool[somenumber];的东西代替

std::vector<bool> isBitXset(somenumber, false);
Run Code Online (Sandbox Code Playgroud)

但我不能这样做

legacyFunction(somenumber, isBitXSet.data());
Run Code Online (Sandbox Code Playgroud)

因为data()不存在std::vector<bool>.我无法改变界面legacyFunction().

有没有一个很好的替代C风格的bool阵列?

Vit*_*meo 7

你可以使用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;
}
Run Code Online (Sandbox Code Playgroud)

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

struct my_bool { bool _b; };
std::vector<my_bool> v; // will not use `vector<bool>` specialization
Run Code Online (Sandbox Code Playgroud)

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

  • @ Rakete1111:如果`somenumber`是运行时值,则不是,如示例中所示. (4认同)