Pushing an array into a vector

后端 未结 8 1443
一整个雨季
一整个雨季 2020-12-17 01:26

I\'ve a 2d array, say A[2][3]={{1,2,3},{4,5,6}}; and I want to push it into a 2D vector(vector of vectors). I know you can use two for loops to pus

8条回答
  •  别那么骄傲
    2020-12-17 02:00

    This is a little tricky, but you could use template recursion to help you in having the assignment done almost completely at compile-time. I understand that's not exactly what you are looking for, but I think it's worthwhile :-)

    Here's the code:

    #include 
    
    using namespace std;
    
    typedef vector > vector2d;
    
    template
    struct v_copy {
        static void copy(vector2d& v, int(&a)[M][N])
        {
            v[K - 1].assign(a[K - 1], a[K - 1] + N);
            v_copy::copy(v, a);
        }
    };
    
    template
    struct v_copy<1, M, N> {
        static void copy(vector2d& v, int(&a)[M][N])
        {
            v[0].assign(a[0], a[0] + N);
        }
    };
    
    template
    void copy_2d(vector2d& v, int(&a)[M][N])
    {
        v_copy::copy(v, a);
    }
    
    int main()
    {
        int A[2][3] = {{0, 1, 2}, {10, 11, 12}};
        vector2d vector(2);
    
        copy_2d(vector, A);
    }
    

    it needed a struct because in C++ you can't do partial specialization of functions. BTW , compiling it with gcc version 4.5.0, this code produces the same assembly as

    vector[1].assign(A[1], A[1] + 3);
    vector[0].assign(A[0], A[0] + 3);
    

    It should not be very hard to have it compile with different types of 2-dimensions arrays.

提交回复
热议问题