这似乎是一个愚蠢的问题,但它真的困扰着我。
基本上,我有一个需要转换为二维数组的一维数组。基本上,数组的大小是:62017 现在从这个,我需要得到这个的行和列。但是,动态地执行此操作,例如,它会采用 43101 的数量,然后建立行+列,然后相应地重新调整向量的大小。
我希望我已经解释得足够多,希望有人能提供帮助,谢谢:)
我相信你正在寻找这样的东西。尽管在访问适当的编译器时遇到了一些挑战,但我无法验证...
#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, size_t new_size_1, size_t new_size_2, size_t old_size>
std::array<new_size_1, std::array<T, new_size_2>> twoDimensionify(std::array<T, old_size> p_input)
{
std::array<new_size_1, std::array<T, new_size_2>> returnValue;
int old_i = 0;
for (int i=0; i<new_size_1; i++)
{
for (int j=0; j<new_size_2; j++)
{
returnValue[i][j] = p_input[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;
return 0;
}
这里是老式数组样式(因为我目前无法访问 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;
}