要查找僅包含 0 和 1 的所有固定長度序列,我使用以下代碼:
#include <bits/stdc .h>
typedef long long int lli;
typedef std::vector<lli> vec_lli;
typedef std::vector<std::string> vec_s;
void print_array(vec_s arr) {
std::cout << '[';
int n = arr.size();
for (size_t i = 0; i < n; i ) {
std::cout << arr[i];
if (i < (n - 1)) {
std::cout << ", ";
}
}
std::cout << ']' << std::endl;
}
vec_s get_variants(int n) {
vec_s result = {"0", "1"};
vec_s temp;
temp.reserve(2);
result.reserve(2);
for (int i=0; i < (n - 1); i) {
std::copy(result.begin(), result.end(), temp.end()); // 1
for (int j=0; j < result.size(); j) {
temp[j] = "0";
result[j] = "1";
}
std::copy(temp.begin(),temp.end(), result.end());
temp.clear();
}
return result;
}
int main(int argc, char const *argv[]) {
int n;
std::cin >> n;
vec_s mb = get_variants(n);
print_array(mb);
return 0;
}
但是向量temp是空的,在第 1 行和之后復制之前。所以,我的程式的輸出是 [0111, 1111]。我做錯了什么?
uj5u.com熱心網友回復:
您正在寫信給temp.end()和result.end()。這些迭代器代表“結束”,因此寫入這些迭代器是未定義行為。
您似乎在尋找std::back_inserter. 這將創建一個迭代器,當它被寫入時,它將向您的容器插入一個新元素。
std::copy(result.begin(), result.end(), std::back_inserter(temp));
雖然這回答了發布的問題,但您的代碼中仍然存在其他導致未定義行為的錯誤。
uj5u.com熱心網友回復:
比 using 更直接的方法std::copy是使用.insert():
temp.insert(temp.end(), result.begin(), result.end()); //1
...
result.insert(result.end(), temp.begin(), temp.end()); // 2nd copy
uj5u.com熱心網友回復:
保留不會增加向量大小。
uj5u.com熱心網友回復:
嘗試用 C 編譯器編譯你的程式是行不通的,因為你包含#include <bits/stdc .h>了一個不符合 tC 標準的頭檔案。
你永遠不應該包含這個檔案。絕不。
因此,您正在使用典型的競爭性編程內容,但為什么要包含所有 C 頭檔案而不使用它們。這是浪費時間。
然后,您鍵入典型的廢話競爭性編程縮寫。其中2個,你不使用,為什么要定義它們?
不要再這樣做了。而在 C 中,請使用該using陳述句。
然后,盡管您想要快速,但您還是將arr值傳遞給您的列印函式。這將復制整個向量。
您分配/比較大量 int 與 unsigned int 值。這是你不應該做的。
另外:使用有意義的變數名稱并撰寫注釋。越多越好。
關于演算法。我花了一段時間才意識到您基本上想要創建二進制數。沒有其他的。不幸的是,你以一種非常復雜的方式翻譯了它。
通常,您只需從 0 數到 n-1,然后顯示資料。就這樣。因為數字的長度可能是任意的,我們將使用手動添加數字,就像在一張紙上的 scholl 一樣。很簡單的。
Everthing 然后 biols 到一些代碼行。
請參見:
#include <iostream>
#include <vector>
int main() {
// Read length of binary number to create and validate input
if (int numberOfDigits{}; (std::cin >> numberOfDigits and numberOfDigits > 0)) {
// Here we will store the binary digits, so 0s or 1s
std::vector<int> digits(numberOfDigits,0);
// Som printing helper
std::cout << '[';
bool printComma{};
// We need to print 2^n possible combinations
for (int i = 0; i < (1 << numberOfDigits); i) {
// Print comma, if need
if (printComma) std::cout << ','; printComma = true;
// Print all digits of the binary number
for (const int d : digits) std::cout << d;
// Calculate next binary number
int carry = 0;
for (int index=numberOfDigits -1; index >=0; --index) {
const int sum = digits[index] ((index == (numberOfDigits - 1)?1:0)) carry;
carry = sum / 2;
digits[index] = sum % 2;
}
}
std::cout << ']';
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/378900.html
