c++ - recursive permutations using vector -
i have function suppose return possible permutation of integers inside vector. code based existing code permutation of strings, tried remodeled work on vectors apparently, dont work thought.. i'll appreciate 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 = v1.begin(); != v1.end(); it++){ vector<int> temp1 = v1; temp1.erase(it); //there's runtime error on line vector<int> temp2 = v2; temp2.push_back(*it); permute(temp1, temp2); } return v; }
this original code permutes 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); } }
here 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); } }
Comments
Post a Comment