我的教授让我们编写单个char
队列(没有模板,只有字符),我没有遇到太多麻烦就完成了。现在我用它来编写一个驱动程序(main()),它将打印出序列 ABC 的每个组合。
字符串必须按以下顺序生成:
A
B
C
AA
AB
AC
BA
BB
BC
CA
CB
CC
AAA
AAB
AAC
ABA
ABB
ABC
ACA
ACB
ACC
etc.
队列的 MAX_SIZE = 10,因此应该在大约 25 个字符串后抛出溢出异常。
这里是提示:
Start with A and B and C in the queue.
“Remove it Display it then Add Add Add ”
这有点道理,但我不知道如何让主控制结构在每次知道时都向上转换一个字符长度(例如,一旦所有单个字符移动到双倍,然后移动到三倍,等等)。
最佳答案
这是一种解决方案。足够简单。
Queue q;
q.enqueue('A');
q.enqueue('\n');
q.enqueue('B');
q.enqueue('\n');
q.enqueue('C');
q.enqueue('\n');
for (size_t i = 0; i < 25; ++i) {
size_t len = 0;
char str[256];
char c;
while ((c = q.dequeue()) != '\n')
str[len++] = c;
str[len] = '\0';
std::cout << str << std::endl;
for (size_t j = 0; j < len; ++j)
q.enqueue(str[j]);
q.enqueue('A');
q.enqueue('\n');
for (size_t j = 0; j < len; ++j)
q.enqueue(str[j]);
q.enqueue('B');
q.enqueue('\n');
for (size_t j = 0; j < len; ++j)
q.enqueue(str[j]);
q.enqueue('C');
q.enqueue('\n');
}
关于c++ - 使用容量受限的队列按顺序列出字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9203947/