Software & Finance





Visual C++ Console Application - Permutation using STL next_permutation algorithm





Permutation often considered difficult to implement. However if you use STL algorithm, it would be just 4 lines of code.


Source Code


// permutation.cpp : Defines the entry point for the console application.

//

 

#include <stdio.h>

#include <tchar.h>

#include <algorithm>

#include <string>

#include <iostream>

 

/***

1 = 1

2 = 2

3 = 6

4 = 24

5 = 120

6 = 720

7 = 5040

***/

int _tmain(int argc, _TCHAR* argv[])

{

    std::string str = "1234";

    int count = 0;

    do

    {

        std::cout << str.c_str() << "\n";

        count++;

    } while (std::next_permutation(str.begin(), str.end()) == true);

 

    std::cout << "\n\nCount: " << count << "\n";

      return 0;

}

Output


ABC

ACB

BAC

BCA

CAB

CBA

 

 

Count: 6

Press any key to continue . . .

 

 

1234

1243

1324

1342

1423

1432

2134

2143

2314

2341

2413

2431

3124

3142

3214

3241

3412

3421

4123

4132

4213

4231

4312

4321

 

 

Count: 24

Press any key to continue . . .