Creating N nested for-loops

后端 未结 7 1998
终归单人心
终归单人心 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条回答
  •  猫巷女王i
    2020-12-03 11:26

    Here is a nice little class for a multi-index that can be iterated via a range-based for-loop:

    #include
    
    template
    struct multi_index_t
    {
        std::array size_array;
        template
        multi_index_t(Args&& ... args) : size_array(std::forward(args) ...) {}
    
        struct iterator
        {
            struct sentinel_t {};
    
            std::array index_array = {};
            std::array const& size_array;
            bool _end = false;
    
            iterator(std::array const& size_array) : size_array(size_array) {}
    
            auto& operator++()
            {
                for (int i = 0;i < dim;++i)
                {
                    if (index_array[i] < size_array[i] - 1)
                    {
                        ++index_array[i];
                        for (int j = 0;j < i;++j)
                        {
                            index_array[j] = 0;
                        }
                        return *this;
                    }
                }
                _end = true;
                return *this;
            }
            auto& operator*()
            {
                return index_array;
            }
            bool operator!=(sentinel_t) const
            {
                return !_end;
            }
        };
    
        auto begin() const
        {
            return iterator{ size_array };
        }
        auto end() const
        {
            return typename iterator::sentinel_t{};
        }
    };
    
    template
    auto multi_index(index_t&& ... index)
    {
        static constexpr int size = sizeof ... (index_t); 
        auto ar = std::array{std::forward(index) ...};
        return multi_index_t(ar);
    }
    

    The basic idea is to use an array that holds a number of dim indices and then implement operator++ to increase these indices appropriately.

    Use it as

    for(auto m : multi_index(3,3,4))
    {
        // now m[i] holds index of i-th loop
        // m[0] goes from 0 to 2
        // m[1] goes from 0 to 2
        // m[2] goes from 0 to 3
        std::cout<

    Live On Coliru

提交回复
热议问题