动态创建一个新数组,其中原始数组中的每个项被复制给定次数

Dynamically create a new array where each item in the original array is duplicated the given number of times

本文关键字:数组 复制 一个 创建 新数组 动态 原始      更新时间:2023-10-16

我不希望你为我做整个函数…我只是需要一些建议。

例如,如果我有一个数组:{1,2,3}…

它最终应该看起来像:{1,1,2,2,3,3}

编辑:这是我到目前为止的功能:

int ExpandArray(const int expanded[], const int arrayLength, const int duplicate, int* newSizePtr)
{
    int newLen = arrayLength * duplicate;
    int newArray[] = new newArray[newLen];
    return newArray;
}

这是最终的结果

int* ExpandArray(const int[], const int, const int, int*);
int main
{
     int arr[] = {1, 2, 3};
     int size;
     int * expanded = ExpandArray(arr, 3, 2, &size);
      cout << "{ ";
     for(int i = 0; i < size; i++)
          cout << expanded[i] << " ";
      cout << "}" << endl;
      delete [] expanded;
     cout << endl;
}

int* ExpandArray(const int expanded[], const int arrayLength, const int duplicate, int* newSizePtr)
{
int newLen = arrayLength * duplicate;
*newSizePtr = newLen;
int *newArray = new int[newLen];
for (int i=0; i < newLen; i++) {
    newArray[i] = expanded[i/duplicate];
}


return newArray;
}

试试这个:

void myFunction (int p[], int *q) {
    int pLen = sizeof(p)/sizeof(*p);
    int *q =  (int *) malloc(pLen * sizeof(int));
    for(int i = 0, j = 0; j < pLen; i += 2, j++) {
        q[i] =  p[j];
        q[i+1] = p[j]; 
    }
    for(int i = 0; i < pLen*2; i++) {
        cout << q[i] << " ";
    }
}

运行。

您的需求有点不清楚。duplicate指的是初始数组中单个元素在最终数组中出现的次数吗?我假设这就是基于您目前所拥有的代码的意思。

既然你知道初始数组中的每个元素在最终数组中应该有多少个元素,那么我要做的就是循环遍历初始数组中的每个元素。现在,在每个元素的循环中,将其添加n次(或重复次数)到最终数组中。您可以为最后一个数组使用单独的计数器,因为它需要在一个循环中增加多次。