是否有替换C型布尔数组的标准方法? [英] Is there a standard way to replace a C-style bool array?
本文介绍了是否有替换C型布尔数组的标准方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这段代码中
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());
因为std::vector<bool>
不存在data()
.而且我不能更改legacyFunction()
的界面.
because data()
doesn't exist for std::vector<bool>
. And I cannot change the interface of legacyFunction()
.
C样式布尔数组有很好的替代方法吗?
Is there a good alternative to the C-style bool array?
推荐答案
您可以使用 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
:
Alternatively, you can "trick" std::vector
by creating your own bool
wrapper:
struct my_bool { bool _b; };
std::vector<my_bool> v; // will not use `vector<bool>` specialization
这篇关于是否有替换C型布尔数组的标准方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文