recursive permutations using vector

1.5k Views Asked by At

I have this function that is suppose to return all possible permutation of integers inside the vector. The code is based from an existing code that does a permutation of strings, I tried to remodeled it to work on vectors but apparently, they dont work similarly as I thought.. I'll appreciate any help that you could offer thanks;

vector<vector<int>> permute(vector<int> &v1, vector<int> &v2){
    vector<vector<int>> v;
    if( v1.empty() )
    {
        v.push_back(v2);
        return v;
    }
    for(auto it = v1.begin(); it != v1.end(); it++){
        vector<int> temp1 = v1;
        temp1.erase(it);          //there's a runtime error on this line
        vector<int> temp2 = v2;
        temp2.push_back(*it);

        permute(temp1, temp2);
    } 

    return v;
}

This is the original code that permutes a string.

void string_permutation( std::string& orig, std::string& perm )
    {
        if( orig.empty() )
        {
            std::cout<<perm<<std::endl;
            return;
        }

        for(int i=0;i<orig.size();++i)
        {
            std::string orig2 = orig;

            orig2.erase(i,1);

            std::string perm2 = perm;

            perm2 += orig.at(i);

            string_permutation(orig2,perm2);
        } 
    }
2

There are 2 best solutions below

1
On

Here you go:

   template < typename T>
   void vec_permute( std::vector<T> &orig, std::vector<T> &perm)
   {
       if(orig.empty())
       {
            for( auto &x : perm)
                std::cout<<x;
            std::cout<<"\n";
            return;
       }
       for(typename std::vector<T>::size_type i=0;i <orig.size();++i)
       {
            std::vector<T> orig2(orig);
            orig2.erase(std::find(orig2.begin(),orig2.end(),orig.at(i)));
            std::vector<T> perm2(perm);
            perm2.push_back(orig.at(i));
            vec_permute(orig2,perm2);            
       }
   }

Demo: http://coliru.stacked-crooked.com/a/01ded4b778aa4165

2
On

Iterators can only be used with the container that you instanciated them with