Code to Generate All Possible Combinations of a given Array Not Working

This is a program to generate possible combinations

Somehow everytime I run it - in VS2012 I get this error -

"Expression:Vector Subscript out of range" ?

Can someone please help to get this code working ?

A Big Thank You !!!

:D

#include <iostream>
#include <vector>

class CombinationsGenerator {
std::vector<int> S;
std::vector<int> combination;

void generate_recursive() {
for (int i = 0, e = combination.size(); i < e; ++i)
std::cout << S[combination[i]] << ' ';
std::cout << '\n';

int first;
if (combination.empty())
first = 0;
else {
int last = *combination.rbegin();
first = last + (S[last+1] == S[last] + 1 ? 2 : 1);
}

for (int i = first, end = S.size(); i < end; ++i) {
combination.push_back(i);
generate_recursive();
combination.pop_back();
}
}

public:
// Input: S is a sorted vector
CombinationsGenerator(std::vector<int> const &S) : S(S) {
}

void generate() {
combination.clear();
generate_recursive();
}
};

int main() {
int S_i[] = {1, 2, 3, 5};
CombinationsGenerator(std::vector<int>(S_i, S_i+4)).generate();
}
use the <ctime> library

seed the rand()

srand((unsigned)time(0));

run random number creator

int a = (1 + ) rand() % (24)

(1 +) is optional. without it it'll create 0 -24. with, then 1 - 24;

(24) = max number, min is always 0;
(1 +) is optional. without it it'll create 0 -23. with, then 1 - 24;


Fixed.
(1 +) is optional. without it it'll create 0 -23. with, then 1 - 24;


Hi there, Thank you for the quick reply.

May I please kindly ask if you could correct the code for me ?

I am very very confused with the code at this stage.

:)

Thank You !
Last edited on
Topic archived. No new replies allowed.