将数组的值传递给修改值的函数,然后将其返回到新数组中

时间:2015-10-02 23:02:45

标签: c++ arrays loops pointers

我无法让代码返回正确的数组。 void map接受一个函数,例如tiple,并修改从数组src传递给它的值,然后将新值返回到dst,然后打印出来。我可以得到编译的代码,但它没有返回正确的数组。例如,当它接收[1,2,3,4]时,它返回[0,3,6,9]而不是[3,6,9,12]

typedef int (*intModifier)(int);

int triple(int x){
    return 3*x;
}

void map(intModifier func, int src[], int dst[], int length){
    for(int *i = src; i < src + length; ++i){
    dst[*i] = func(*i);
    }
return;

}

void printIntArray(int arr[], int length){
cout << "{";
    if (length > 0){
    cout << arr[0];
    }
    for(int i = 1; i < length; ++i){
    cout << ", " << arr[i];
    }
    cout << "}";
    }

int main(){

int arr1[4] = {1, 2, 3, 4};
int arr2[4] = {0, 0, 0, 0};
int arr3[4] = {0, 0, 0, 0};
int arr4[4] = {0, 0, 0, 0};

cout << "Testing map." << endl;
cout << "  setting arr1 = {1,2,3,4}" << endl << endl;

cout << "  mapping from arr1 to arr2 using triple" << endl;
map(triple, arr1, arr2, 4);
cout << "  arr2 = ";
printIntArray(arr2, 4);  cout << endl << endl;
return 0;
}

感谢任何帮助。感谢。

2 个答案:

答案 0 :(得分:1)

我不确定为什么它只是被修改的第二个元素。但事实上只有一个几乎肯定是这样的:

void map(intModifier func, int src[], int dst[], int length){
    for(int *i = src; i < src + length; i++){
        dst[*i] = func(src[*i]);
        return; // You return here!!!
    }
}

map循环的第一次迭代期间,您将始终从for返回。看看缩进代码是多么有益!

答案 1 :(得分:0)

您的map功能是导致大多数问题的原因。特别是在您尝试在for循环中执行操作的方式。

void map(intModifier func, int src[], int dst[], int length){
    for(int *i = src; i < src + length; ++i){ // There are some major issues in how you are 
        dst[*i] = func(*i);                   // iterating through the source array.
    }
return;

}

您正在使用源数组的值来增加和存储目标数组和源数组之间的数据。你的数组只有4个int&#34; blocks&#34;然而,你在源基础长度加上4 i < src + length增加源,这远远超过你的数组长度。

如果你使用传入的长度进行迭代会更好,这基本上就是为什么你传递正确的长度?所以你可以用这个:

void map(intModifier func, int src[], int dst[], int length){

    for (int i = 0; i < length; i++) // Iterate until we have met the length of the source
    {                                // array. Pass the source array off to our triple func
        dst[i] = func(src[i]);
    }

    return;
}

该函数遍历源并将其内容传递给triple func,然后将其存储在目标数组中的相同位置。

编辑:归功于 1201ProgramAlarm Ben