c++中添加两个bool数组

c++ adding two bool arrays

本文关键字:两个 bool 数组 添加 c++      更新时间:2023-10-16

我有一个数字作为bool数组,但我需要做算术运算,如加减和逻辑,如AND与其他数字类似。如何在c++中完成这些操作,而不需要处理所有布尔特定的计算,并且做得很简单。示例:

bool a[10];
bool b[10];
bool c[10];
c = a + b; 

您可以使用std::bitset

#include <bitset>
std::bitset<10> a(4);
std::bitset<10> b("0000001000");
std::bitset c = a.to_ulong() + b.to_ulong();
//Etc.
//You can also use
a[0] = 4; a[1] = 5; //to initialize / access

std::transform可以对来自两个容器的元素对执行二进制操作,并将结果放入第三个容器。您可以使用std::logical_andstd::logical_or来获得您想要的结果:

transform(a, a+10,
          b, b+10,
          c, logical_and<bool>());
transform(a, a+10,
          b, b+10,
          c, logical_or<bool>());