请求协助实现按指定顺序重写数组的shuffle函数
解决数组按指定顺序重写的问题
首先分析你现有代码的核心问题:
- 第二个
for循环中手动修改循环变量i,会和循环自身的i++逻辑冲突,导致大量索引被跳过。 - 循环仅处理了
i==0的场景,其余索引的wy元素未被赋值,因此只有第一个元素能正确输出。
以下是符合需求的完整实现,包含独立的shuffle函数,并假设你需要的“指定顺序”为前5个元素(索引0-4)与索引6-10的元素交叉写入,最后放入索引5的元素(可根据实际需求调整顺序逻辑):
#include <iostream> #include <cstdlib> // 用于rand() using namespace std; // 实现需求的shuffle函数 void shuffle(int* we, int count, int* wy) { int wyIndex = 0; // 交叉写入i<5和i>5的元素 for (int i = 0; i < 5; ++i) { wy[wyIndex++] = we[i]; // 写入we[0]到we[4] if (i + 6 < count) { // 确保不越界,写入we[6]到we[10] wy[wyIndex++] = we[i + 6]; } } // 写入中间的i=5元素 if (5 < count) { wy[wyIndex] = we[5]; } } void zadanie1(void) { int count = 11; int* we = new int[count]; int* wy = new int[count]; cout << "Begin: " << endl; for (int i = 0; i < count; ++i) { we[i] = rand() % 10; cout << we[i] << " "; } cout << endl; // 调用shuffle函数处理数组 shuffle(we, count, wy); cout << "End: " << endl; for (int i = 0; i < count; ++i) { cout << wy[i] << " "; } cout << endl; // 释放动态分配的内存,避免泄漏 delete[] we; delete[] wy; } int main() { zadanie1(); return 0; }
关键说明
- 用独立的
wyIndex控制wy数组的写入位置,避免修改循环变量导致的逻辑混乱。 - 保留了数组越界判断,让
shuffle函数更通用,适配不同的count值。 - 添加了动态内存释放逻辑,修复原代码的内存泄漏问题。
如果你的“指定顺序”是其他规则,仅需修改shuffle函数内的赋值逻辑即可。例如要将后6个元素放在前面、前5个放在后面:
void shuffle(int* we, int count, int* wy) { int wyIndex = 0; // 先写入i>5的元素(索引6-10) for (int i = 6; i < count; ++i) { wy[wyIndex++] = we[i]; } // 再写入i<5的元素(索引0-4) for (int i = 0; i < 5; ++i) { wy[wyIndex++] = we[i]; } // 最后写入i=5的元素 wy[wyIndex] = we[5]; }
内容的提问来源于stack exchange,提问作者Freshu
相关产品推荐
相关产品推荐

