Recursive generator in C++

前端 未结 5 1195
星月不相逢
星月不相逢 2021-02-06 11:13

I have a vector of size = N where each element i can have values from 0 to possible_values[i]-1. I want to do a function that iterates me through all those values.

I was

5条回答
  •  走了就别回头了
    2021-02-06 11:37

    Yet another:

    #include 
    #include 
    
    typedef std::vector uint_vector;
    typedef std::vector values_vector;
    
    values_vector all_values (const uint_vector & ranges, unsigned int pos=0) {
       values_vector result;
       if (pos == ranges.size()) {
          result.push_back (uint_vector());
       }   
       else {
          values_vector rem_result = all_values (ranges, pos+1);
          for (unsigned int v = 0; v < ranges[pos]; ++v) {
             for (auto it : rem_result) {
                result.push_back (uint_vector(1,v));
                result.back().insert (result.back().end(), it.begin(), it.end());
             }
          }      
       }      
       return result;
    }      
    
    void print_values (const values_vector & combos) {
       for (auto combo : combos) {
          std::cout << "[ "; 
          for (auto num : combo) {
             std::cout << num << ' ';
          }      
          std::cout << "]\n";
       }      
    }      
    
    int main () {
       uint_vector ranges {3,2,2};
       print_values (all_values (ranges));
       return 0;
    }      
    

    Implementation at ideone.com

提交回复
热议问题