[英]What does this C++ for-loop expression mean?
我正在解決 leetcode 上的“添加二進制”問題,我在網上找到的解決方案如下:
#include <string>
using std::string;
class Solution {
public:
string addBinary(string a, string b) {
string ret;
bool carry{false};
for (auto apos=a.size(), bpos=b.size(); apos || bpos || carry; ) {
bool abit{apos && a[--apos] == '1'};
bool bbit{bpos && b[--bpos] == '1'};
ret = (abit ^ bbit ^ carry ? "1" : "0") + ret;
carry = abit + bbit + carry >= 2;
}
return ret;
}
};
我的問題是關於上面的 for 循環。 我知道使用逗號分隔的前兩個表達式實例化了兩個迭代。 但是,我不明白三個被或的單位(即:||)應該如何表現。 我也很好奇為什么在這種情況下可以排除迭代器表達式,即for循環中的最終表達式。 請幫助我了解此代碼的功能。
基本上 for 循環由 3 個部分組成,由 ';'(分號)分隔
1)第一部分,這部分是關於變量的初始化,如果你願意,你可以離開它
2)第二部分,它定義了for循環將繼續運行的條件,如果你願意,你也可以離開它
3)第三部分,這是你想要做一些操作的部分,通常迭代值是增量,但如果你願意,你也可以離開它
因此,如果您使用此 model go,我認為您可以輕松分解您提到的 for 循環中發生的事情。
有時考慮等效的 while 循環會有所幫助:
for (auto apos=a.size(), bpos=b.size(); apos || bpos || carry; /*no increment*/) {
// ...
}
->
{
auto apos = a.size();
auto bpos = b.size();
while( apos || bpos || carry ) {
bool abit{apos && a[--apos] == '1'};
bool bbit{bpos && b[--bpos] == '1'};
ret = (abit ^ bbit ^ carry ? "1" : "0") + ret;
carry = abit + bbit + carry >= 2;
/* increment would be here*/
}
}
循環初始化apos
和bpos
並繼續循環,只要條件apos || bpos || carry
apos || bpos || carry
apos || bpos || carry
產生true
,即只要apos
、 bpos
和carry
不全為0
( 0
轉換為false
任何其他數字為true
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.