Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

c++ - how to use 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

std::next_permutation returns the next permutation in lexicographic order, and returns false if the first permutation (in that order) is generated.

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

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;
}

Here is a live example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...