创建N个嵌套for循环

And*_*rew 13 c++ algorithm recursion for-loop nested-loops

有没有办法创建表单的for循环

for(int i = 0; i < 9; ++i) {
    for(int j = 0; j < 9; ++i) {
    //...
        for(int k = 0; k < 9; ++k) { //N-th loop
Run Code Online (Sandbox Code Playgroud)

在编译时不知道N. 理想情况下,我试图找出一种循环通过数字向量的单独元素的方法,以便在用不同的数字替换一定数量的数字时创建每个可能的数字.

Raz*_*zib 13

您可以使用递归而不是基本条件 -

void doRecursion(int baseCondition){

   if(baseCondition==0) return;

   //place your code here

   doRecursion(baseCondition-1);
}  
Run Code Online (Sandbox Code Playgroud)

现在您不需要baseCondition在编译时提供值.您可以在调用doRecursion()方法时提供它.


dav*_*igh 5

这是一个很好的小类,可以通过基于范围的for循环迭代多索引:

#include<array>

template<int dim>
struct multi_index_t
{
    std::array<int, dim> size_array;
    template<typename ... Args>
    multi_index_t(Args&& ... args) : size_array(std::forward<Args>(args) ...) {}

    struct iterator
    {
        struct sentinel_t {};

        std::array<int, dim> index_array = {};
        std::array<int, dim> const& size_array;
        bool _end = false;

        iterator(std::array<int, dim> 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<typename ... index_t>
auto multi_index(index_t&& ... index)
{
    static constexpr int size = sizeof ... (index_t); 
    auto ar = std::array<int, size>{std::forward<index_t>(index) ...};
    return multi_index_t<size>(ar);
}
Run Code Online (Sandbox Code Playgroud)

基本思想是使用包含许多dim索引的数组,然后实现operator++适当增加这些索引.

用它作为

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<<m[0]<<" "<<m[1]<<" "<<m[2]<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)

Live On Coliru