I know that I can use std::next_permutation
on some container containing the elements [1, 2, 3]
which would generate 6 permutations of this sequence. What I would like to do is given some set [1, 2, 3, 4, 5, 6]
generate all possible permutations of size 3. So for this example, [4, 3, 2]
would be one of the permutations resulting from this criteria. I'm looking for an STL way of doing this (if possible) rather than writing my own combinations function. Any particular STL implementation I should be reading about ?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- What are the problems associated to Best First Sea
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
There is currently (as of 2016) no single STD function to do that. The closest you have is the proposal from http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2639.pdf
The function you want is called
next_partial_permutation
and looks like (from N2639):This is not the most efficient possible algorithm but it's easy. You must start with the elements sorted. To get the next k-permutation, reverse the last n-k elements and then try to get the next permutation. The first k elements are the next k-permutation.
Here is an algorithm written in Smalltalk.
The idea of the algorithm is to consider the lexicographic order of arrays of length
m
with elements between1
andn
. Given any sucharray
, the methodnext
replacesarray
with its next partial permutation in said order.I've created a class with three instance variables
The instance creation method
m:n:
works as followsIn this class the method
next
modifies thearray
so that it will now hold the next permutation.It might be worth mentioning that the algorithm is not recursive.
The method
next
answers withnil
iffarray
contains the last permutation in the order (i.e.,array = (n, n-1, ...., n-m+1)
.To compute all permutations start with
array = (1 ... m)
and sendnext
until the answer isnil
.Where