next-combination-in-cpp

C++ STL do not have a function that can present certain combination of elements. But this can be achieved by utilizing the STL function next_permutation() with boolean arrays. Suppose choosing 5 elements out of 2, the combination can be started with a function [0,0,0,1,1] and then loop with next_permutation to identify whether to choose an element or not.

example:

1
2
3
4
5
int c[] = {0,0,0,1,1};
do{
for (int i = 0;i < 5; i++) printf("%d",c[i]);
printf("\n");
}while(next_permutation(c,c+5));

the above code can produce the result below:

1
2
3
4
5
6
7
8
9
10
00011
00101
00110
01001
01010
01100
10001
10010
10100
11000

and the produced bool array can be used to choose elements.