动态创建一个新数组,其中原始数组中的每个项被复制给定次数
Dynamically create a new array where each item in the original array is duplicated the given number of times
我不希望你为我做整个函数…我只是需要一些建议。
例如,如果我有一个数组:{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次(或重复次数)到最终数组中。您可以为最后一个数组使用单独的计数器,因为它需要在一个循环中增加多次。
相关文章:
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 将字符数组复制到 QByte 数组中,而无需传递指针
- std::transform 将一个结构数组复制到另一个结构数组
- 如何使用指针C++将元素从2D数组复制到1D数组
- 如何将 int4 数组复制到 int8 向量中
- 如何将多维字符数组复制到字符 * 中
- std::将三维数组复制到三维向量中
- 为什么我不能将 C 样式数组复制到 std::array?
- 有没有办法将最初作为字符串输入的数字字符数组复制到双向链表中
- 为什么当我想将(使用 memcpy)结构数组复制到字符数组时,字符数组为空
- 如何将数据从数组复制到C++特征矩阵或向量
- 将数组复制C++作为特征矩阵的向量
- 如何在 c++ 中将数组复制到文件
- 如何将对象数组作为构造函数中的参数传递,然后将传递的数组复制到另一个数组(仍在构造函数中)
- CUDA 将大于线程计数的数组复制到共享内存
- 可以使用 std::copy 将 3D 数组复制到矢量
- 如何在C++中将本地字符串数组复制到私有成员字符串数组
- 如何使用 std::copy 将一个 constexpr 数组复制到另一个 constexpr 数组
- 如何将 char 类型数组传递给函数并将第一个字符数组复制到第二个图表数组并使用 c++ 进行比较