给定一个稀疏 vector (比其他元素多 0),创建一个函数将 vector 分成两个 vector (一个包含元素,另一个包含元素的位置。创建另一个函数来重建源 vector 来自位置和值数组(包括原始来源中的 0)。
所以这并没有正确地重建它 - 我不明白为什么。我在 main 函数中测试了数组 val 和 pos,但它们中的数字不正确。
这是我目前所拥有的:
为了有效表示(将源 vector 分成两部分):
void efficient( const int source[], int val[], int pos[], int size)
{
int j = 0;
for (j = 0; j < size; j++)
{
if (source[j] != 0)
{
val[j] = source[j];
pos[j] = j;
}
}
}
对于重建函数(m 是被重建的源 vector 的大小,n 是位置和值 vector 的大小):
void reconstruct( int source[], int m, const int val[], const int pos[], int n) {
int i = 0;
int j = 0;
int k = 0;
for (i = 0; i < m; i++)
source[i] = 0; // sets all elements in source array equal to 0
for (j = 0; j < n; j++){
source[pos[j]] = val[j];
}
for (k = 0; k < m; k++)
printf("%d ", source[k]);
}
这是我的主要测试函数:
int main()
{
int i;
int size;
const int source[] = {0,0,23,0,-7,0,0,48};
int val[3] ;
int pos [3] ;
efficient(source,val,pos,8); // calls function efficient
reconstruct(source, 8, val, pos, 3); // calls function reconstruct with parameters source, source size = 8, value array, position array and size of value and position array
}
所以这并没有正确地重建它 - 我不明白为什么。我在 main 函数中测试了数组 val 和 pos,但它们中的数字不正确。
最佳答案
void efficient( const int source[], int val[], int pos[], int size)
{
int j = 0;
for (j = 0; j < size; j++)
{
if (source[j] != 0)
{
val[j] = source[j]; <-- HERE
pos[j] = j;
}
}
}
你不是说 val[j]
。您需要一个单独的变量来计算 val 和 pos 中的条目数。也许:
void efficient( const int source[], int val[], int pos[], int size)
{
int j, p;
for (j = 0, p = 0; j < size; j++)
{
if (source[j] != 0)
{
val[p] = source[j];
pos[p] = j;
++p;
}
}
}
关于c - 在c中重建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26285162/