Creating N nested for-loops

后端 未结 7 2010
终归单人心
终归单人心 2020-12-03 11:16

Is there a way to create for-loops of a form

for(int i = 0; i < 9; ++i) {
    for(int j = 0; j < 9; ++i) {
    //...
        for(int k = 0; k < 9; +         


        
7条回答
  •  余生分开走
    2020-12-03 11:29

    I use this solution:

    unsigned int dim = 3;
    unsigned int top = 5;
    std::vector m(dim, 0);
    for (unsigned int i = 0; i < pow(top,dim); i++)
    {
        // What you want to do comes here 
        //      |
        //      |
        //      v
        // -----------------------------------
        for (unsigned int j = 0; j < dim; j++)
        {
            std::cout << m[j] << ",";
        }
        std::cout << std::endl;
        // -----------------------------------
    
        // Increment m
        if (i == pow(top, dim) - 1) break;
        unsigned int index_to_increment = dim - 1;
        while(m[index_to_increment] == (top-1)) {
            m[index_to_increment] = 0;
            index_to_increment -= 1;
        }
        m[index_to_increment] += 1;
    }
    

    It can certainly optimized and adapted, but it works quite well and you don't need to pass parameters to a recursive function. With a separate function to increment the multi-index:

    typedef std::vector ivec;
    void increment_multi_index(ivec &m, ivec const & upper_bounds)
    {
        unsigned int dim = m.size();
        unsigned int i = dim - 1;
        while(m[i] == upper_bounds[i] - 1 && i>0) {
            m[i] = 0;
            i -= 1;
        }
        m[i] += 1;
    }
    
    int main() {
    
        unsigned int dim = 3;
        unsigned int top = 5;
        ivec m(dim, 0);
        ivec t(dim, top);
        for (unsigned int i = 0; i < pow(top,dim); i++)
        {
            // What you want to do comes here 
            //      |
            //      |
            //      v
            // -----------------------------------
            for (unsigned int j = 0; j < dim; j++)
            {
                std::cout << m[j] << ",";
            }
            std::cout << std::endl;
            // -----------------------------------
    
            // Increment m
            increment_multi_index(m, t);
        }
    
    }
    

提交回复
热议问题