Can I get rid of nested for loops here?

  • A+
Category:Languages

I have a function that takes a vector and returns a vector by combining all the elements in it. Right now, I have 3 nested for loops that create a combination that is 3 levels deep. I would like it to look better and have the ability to add the functionality to make it 4 levels deep when I want.

If input = ["one", "two", "three"]

3 level output = "onetwothree" "twoonethree" and so on.

std::vector<std::string> generator(std::vector<std::string>& x) {     std::vector<std::string> output;     std::string tmp;     for (auto i : x) {         output.push_back(i);         for (auto j : x) {             tmp = i + j;             output.push_back(tmp);             for (auto k : x) {                 tmp = i + j + k;                 output.push_back(tmp);             }         }     }     return output; } 

I have looked into iterators, but I can't figure out if it would work.

 


If what you are looking for is to simply generate the permutations of all the elements of the string vector x and store these permutations into another output vector, this is easily accomplished by using std::next_permutation and std::accumulate:

#include <vector> #include <string> #include <numeric> #include <iostream> #include <algorithm>  std::vector<std::string> generator(std::vector<std::string> x) {     std::vector<std::string> output;     std::sort(x.begin(), x.end());     do      {         output.push_back(std::accumulate(x.begin(), x.end(), std::string()));     } while (std::next_permutation(x.begin(), x.end()));     return output; }  int main() {     auto v = generator({"one","two","three"});     for (auto& val : v)         std::cout << val << "/n"; }     

Live Example

The std::accumulate basically calls operator + on the elements by default, thus the string is automatically concatenated.

As far as std::next_permutation, the description of what it does is explained at the link. Basically you want to start out with a sorted sequence, and call std::next_permutation to get the next permutation of elements.

Note that this is not contingent of the number of "levels" (as you call it). You could have a vector of 10 strings, and this would work correctly (assuming there are no memory constraints).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: