DataMiner
DataMiner

Reputation: 325

Generating all possible combination of the elements of integer vector in c++

I have an integer vector of size "n".

e.g.
std::vector<int> vec;
vec.pushback(0);
vec.pushback(1);
vec.pushback(2);
vec.pushback(3);
....

Now i want to generate all possible combinations of size = {0, 1, 2, ... , n}.

please keep in mind that {0, 1, 3} is not equal to {3, 1, 0} or {1, 0, 3} or {3, 0, 1}

Please help me if you have an idea.

Thanks in advance.

Upvotes: 1

Views: 1780

Answers (1)

Tony The Lion
Tony The Lion

Reputation: 63200

You could do something like this:

#include<iostream>
#include<algorithm>
#include <vector>

    std::ostream& operator<< (std::ostream& os, std::vector<int> v)
    {
        for (auto it = v.begin(); it != v.end(); ++it)
        {
           os << *it << ",";
        }
        return os;
    }

int main()
{
   std::vector<int> v;
   v.push_back(1);
   v.push_back(2);
   v.push_back(3);
    do {
       std::cout << v;
    } while (std::next_permutation(v.begin(), v.end()));

}

As per @JamesKanze's comment, this can only work if the vector is sorted to begin with, so if you have an unsorted vector, you should call std::sort on it first.

Looking at this, it says:

Transforms the range [first, last) into the next permutation from the set of all permutations that are lexicographically ordered with respect to operator< or comp.

You can see it in action here

Upvotes: 2

Related Questions