-2

I have a number of variables of type User. All objects of this type are located in a set. The number of these variables is not fix so I only can determine it at runtime. Therefore I have a variable number of Iterators. I save them in the following list.

list<set<User>::iterator> userIterators;

for (unsigned int i = 0; i < numberOfUserParameters; i++) {

userIterators.push_back(q->getUserSet()->getUsers().begin()); }

Now I need to get all possible combinations of these n UserIterators. (I know about its computional complexity.)

Of course, if I would only have four parameters, I would write four nested loops but what can I do in this variable case with n parameters?

Thanks in advance!

EDIT:

Here is an example.

numberOfUserParameters = 3, set< User > = { U1, U2 }

So I expect all triples set< User > X set< User > X set< User >, the cartesian product with other words.

lukasl1991
  • 241
  • 3
  • 11

1 Answers1

0

Quick solution:

int num_iters = 4;   //something random
int max_index = 2;   //something random too
std::vector<int> indices(num_iters);

do
{
    for(int i=0; i<num_iters; ++i)
    {
        if(indices[i]<max_index)
        {
            ++indices[i];
            break;
        }
        else
        {
            indices[i] = 0;
        }
    }

    //here use indices as your current combination, e.g.
    for(int i=0;i<num_iters;++i)
    {
        std::cout<<indices[i]<<" ";   
    }
    std::cout<<std::endl;
}
while(!std::all_of(indices.begin(), indices.end()
     , [max_index](auto x) { return x == max_index; }));

DEMO

You can further transform this logic from discrete indices to your set (whereas I'd rather use a vector of iterators instead of a set) -- just replace the check indices[i]<your_size-1 by a test for .end(), and the line indices[i] = 0 by an assignment to .begin().

davidhigh
  • 14,652
  • 2
  • 44
  • 75