gpt4 book ai didi

c++ - 将一维转换为二维?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:54:31 25 4
gpt4 key购买 nike

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

基本上,我有一个一维数组,我需要将其转换为二维数组。基本上,数组的大小是:62017 现在从这里,我需要得到它的行和列。但是,动态地执行此操作,例如,它会采用数字 say:43101,然后建立行+列,然后相应地重新调整 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;
}

关于c++ - 将一维转换为二维?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11963391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com