如何使用next_permutation [英] how to use next_permutation

查看:75
本文介绍了如何使用next_permutation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试安排井字游戏板.所以我有以下代码:

I'm trying to get an arrangement of tic tac toe boards. So I have the following code:

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

但是它只输出一次原始字符串.我假设每个字符都必须是唯一的.我该怎么做?

But it only outputs the original string once. I'm assuming that each character has to be unique. What's a way I can do this?

推荐答案

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

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

Since the string you start with ("xxxxxoooo") is actually the last permutation of that string's characters in lexicographic order, your loop stops immediately.

因此,您可以尝试对moves进行排序,然后再开始循环调用next_permutation():

Therefore, you may try sorting moves before starting to call next_permutation() in a loop:

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

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

这是一个 实时示例 .

这篇关于如何使用next_permutation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆