gpt4 book ai didi

c++ - 仅由数字 0-9 组成的四字符字符串的排列

转载 作者:行者123 更新时间:2023-11-27 23:42:13 25 4
gpt4 key购买 nike

您好,感谢阅读我的问题。我希望弄清楚如何存储仅由数字组成的 4 个字符串的所有可能排列,可以重复。

char str[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

sort(begin(str), end(str));
do{
cout << str[0] << ' ' << str[1] << ' ' << str[2] << ' ' << str[3] << '\n';
}while(next_permutation(begin(str), end(str)));

上面的代码是我现在拥有的。它打印排列,但我不确定如何存储它们。它还循环经过我需要的排列,在 9999 之后它似乎重新开始。我正在寻找一种将“0000”、“0001”、“0002”、“0003”、“0004”、......、“9999”(0000-9999)存储到字符串 vector 中的方法。我必须在没有递归的情况下执行此操作,并且接受使用 STL。

最佳答案

只需将数字 0 到 9999 存储在字符串 vector 中。无需使用 next_permutation。

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main(int argc, char* argv[]) {
vector<string> nums;

for(int i = 0; i < 10000; ++i) {
string num = to_string(i);
nums.push_back(string(4 - num.length(), '0') + num);
}

for(string& s: nums) {
cout << s << " ";
}
cout << endl;

return 0;
}

关于c++ - 仅由数字 0-9 组成的四字符字符串的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53730704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com