如何使用next_permutation

时间:2013-05-21 22:08:52

标签: c++ permutation

我试图安排tic tac toe board。所以我有以下代码:

// 5 turns for x if x goes first
std::string moves = "xxxxxoooo";

do {
    std::cout << moves << std::endl;
} while ( std::next_permutation(moves.begin(), moves.end()) );

但它只输出一次原始字符串。我假设每个角色都必须是唯一的。我能做到这一点的方式是什么?

1 个答案:

答案 0 :(得分:18)

std::next_permutation以字典顺序返回下一个排列,如果生成第一个排列(按此顺序),则返回false

由于您以("xxxxxoooo")开头的字符串实际上是字典顺序中该字符串字符的最后一个排列,因此您的循环会立即停止。

因此,您可以尝试在开始在循环中调用moves之前对next_permutation()进行排序:

std::string moves = "xxxxxoooo";
sort(begin(moves), end(moves));

while (std::next_permutation(begin(moves), end(moves)))
{
    std::cout << moves << std::endl;
}

这是live example

相关问题