这似乎是一个愚蠢的问题,但这确实困扰着我。

基本上,我需要将1D数组转换为2D数组。基本上,数组的大小是:现在从62017开始,我需要获取此行和列。但是,要动态地执行此操作,因此,例如,它将要说的数目为:43101,然后建立row + cols,然后相应地调整 vector 的大小。

我希望我已经解释够了,希望有人可以提供帮助,谢谢:)

最佳答案

这是老式的数组风格(因为目前无法访问C++ 0x编译器)

#include <iostream>
//#include <array>
#include <inttypes.h>
#include <math.h>

void calc_new_sizes(const size_t old_size, size_t& new_size1, size_t& new_size2)
{
    new_size1 = 1;
    new_size2 = 1;
    size_t stop_at = (size_t)sqrt(old_size) + 1;
    for (size_t i = 1; i<stop_at; i++)
    {
        if ( old_size % i == 0 )
        {
            new_size1 = i;
            new_size2 = old_size / i;
        }
    }
}

template <class T>
T** twoDimensionify(T* p_old_array, const size_t old_size)
{
    size_t new_size1=1, new_size2=1, old_i=0;
    calc_new_sizes(old_size, new_size1, new_size2);
    T** returnValue = new T*[new_size1];
    for (size_t i=0; i<new_size1; i++)
    {
        returnValue[i] = new T[new_size2];
        for (size_t j=0; j<new_size2; j++)
        {
            returnValue[i][j] = p_old_array[old_i];
            old_i++;
        }
    }
    return returnValue;
}

int main()
{
    size_t old_size=20, new_size1=0, new_size2=0;
    calc_new_sizes(old_size, new_size1, new_size2);
    std::cout << "From " << old_size << " to " << new_size1 << "x" << new_size2 << std::endl;

    int old_array[20] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
    int **new_array = twoDimensionify<int>(old_array, 20);
    for (size_t i=0; i<new_size1; i++)
    {
        for (size_t j=0; j<new_size2; j++)
        {
            std::cout << "new array[" << i << "," << j << "] = " << new_array[i][j] << std::endl;
        }
    }

    // Clean up my memory.  This is C++ afterall.
    for (size_t i=0; i<new_size1; i++)
    {
       delete [](new_array[i]);
    }
    delete []new_array;
    return 0;
}

10-04 14:26