我想添加两个bolean向量
vector<bool> v1= {0,0,1}
vector<bool> v2= {1,0,1}
vector<bool> resultedVector = v1+v2
答案应该是:
resultedVector = {1,1,0};
有谁知道,怎么办c++/c++11
?
我希望每次给定布尔向量增加1.并且只想使用二进制运算。或者可以创建给定数量的变量的波浪真值表。
答案 0 :(得分:0)
要在C ++中执行二进制加法,您可以使用此处描述的函数: Adding binary numbers in C++
我从该链接实现了该功能,以符合您的规范:
std::vector<bool> add(const std::vector<bool>& a, const std::vector<bool>& b)
{
bool c;
std::vector<bool> result;
for(int i = 0; i < a.size() ; i++){
result.push_back(false);
result[i] = ((a[i] ^ b[i]) ^ c); // c is carry
c = ((a[i] & b[i]) | (a[i] & c)) | (b[i] & c);
}
return result;
}
此函数采用两个bool向量(并假设它们具有相同的大小)并返回其结果向量。显然,这个功能不能处理溢出或不同大小的数量。如果需要这些功能,您可以自己修改它。此外,您似乎在谈论bool向量的重载运算符,您可以通过检查运算符重载来实现,但此逻辑将允许您添加存储在向量中的两个布尔值。
答案 1 :(得分:0)
以下是如何使用有状态仿函数的方法:
struct BitAdder {
bool carry_ = 0x0; // Range is [0, 1].
// Only accepts single bit values for a and b.
bool operator()(bool a, bool b) {
assert(a == (a & 0x1) && b == (b & 0x1));
char sum = a + b + carry_;
carry_ = (sum & 0x2) >> 1; // Keep in range.
return sum & 0x1;
}
};
// Code is more straightforward when bits are stored in reverse.
std::vector<bool> v = {0, 1, 1, 1, 0}; // To be interpreted as: 1110 (14).
std::vector<bool> w = {1, 0, 1, 1, 0}; // To be interpreted as: 1101 (13).
std::vector<bool> result = {0, 0, 0, 0, 0}; // Will become: 11011 (27).
assert(v.size() <= w.size()); // v and w can be iterated over together.
assert(v.size() <= result.size()); // There is enough space to store the bits.
assert(v[v.size() - 1] + w[v.size() - 1] < 2); // No overflow can happen.
std::transform(v.cbegin(), v.cend(), w.cbegin(), result.begin(), BitAdder());
std::cout << "want: 11011, got: ";
std::copy(result.crbegin(), result.crend(), std::ostream_iterator<bool>(std::cout));
std::cout << '\n';
答案 2 :(得分:0)
我不确定我理解你的问题。由于这看起来像家庭作业,问题的关键似乎是运营商超载,这是一个想法,而不是完整的答案:
body{
background: url('https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=750&h=350') center top 0 no-repeat / cover;
}
.wrapper {
max-width: 400px;
margin: 30px auto 0;
border: 2px dotted red;
height: 200px;
border-top: 0;
text-align: center;
}
.heading {
display: table;
width: 100%;
position: relative;
}
.heading:before {
content: '';
display: table-cell;
border-top: 2px dotted red;
}
.heading:after {
content: '';
display: table-cell;
border-top: 2px dotted red;
}
.txt-wrapper {
display: table-cell;
width: 1%;
white-space: nowrap;
line-height: 0;
padding: 0 10px;
}
编辑 - 一天后
以下是增量问题(demo)的解决方案:
<div class="wrapper">
<div class="heading">
<h2 class="txt-wrapper">
This is heading
</h2>
</div>
<P>
This is paragraph.
</P>
<P>
This is another paragraph.
</P>
</div>