如何使用next_permutation

how to use next_permutation

本文关键字:permutation next 何使用      更新时间:2023-10-16

我想要一个井字游戏板的安排。所以我有下面的代码:

// 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()) );

但是它只输出原始字符串一次。我假设每个角色都是独一无二的。我该怎么做呢?

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

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

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

std::string moves = "xxxxxoooo";
sort(begin(moves), end(moves));
while (std::next_permutation(begin(moves), end(moves)))
{
    std::cout << moves << std::endl;
}

下面是一个的实例