c++ - 关于 C++ 中的数组和移动元素
问题描述
我正在练习我的 C++ 技能,我提出了一个问题。我有一个包含 20 个元素的数组,其中 10 个在 EX 之前声明:list[1,2,3,4,5,6,7,8,9,10]。我的工作是编写一个函数,插入最后一个元素,但在 EX 现有元素的每个元素之后:list[1, 0, 2, 8, 3, 9, 4, 10, 5 ...] 等。
我所做的是将最后 10 个元素声明为 0
void insertNum(int list[], int &count){
srand(time(NULL));
count = 20;
int temp = 0;
int i, j, min;
for (int i = 10; i < count; i++) {
list[i] = 0;
}
}
但我找不到完整的解决方案,这让我很生气。关于如何做的任何想法?
这是整个代码
#include <iostream>
#include <ctime>
using namespace std;
const int CAP = 20;
void buildList(int[], int &count);
void printList(int[], int count);
void insertNum(int list[], int &count);
int main(){
int list[CAP], count = 0;
buildList(list, count);
cout << "Original List!" << endl;
printList(list, count);
insertNum(list, count);
cout << "List after inserts!" << endl;
printList(list, count);
return 0;
}
void buildList(int list[], int &count){
srand(time(NULL));
count = 10;
for (int i = 0; i < count; i++)
{
list[i] = rand() % 100;
}
}
void printList(int list[], int count){
for (int i = 0; i < count; i++)
{
cout << list[i] << endl;
}
}
void insertNum(int list[], int &count){
}
解决方案
我没有完全理解这个问题,但如果我是对的,你想创建一个函数,在现有数组的每个元素之后插入一个元素。这可能是您正在寻找的。如果不是,请重新表述问题。
srand(time(NULL)); // need to do in main function only.
int oldArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int finalArray[20] = { 0 };
for (int i = 0; i < 20; i++)
{
int newElement = rand()%11+10; //random number between 10 to 20. Figure out what and from where new element will come from
if (i % 2 == 0)
finalArray[i] = oldArray[i / 2];
else
finalArray[i] = newElement;
}
推荐阅读
- r - 在保留注释的同时解析 R 表达式
- php - 注意:尝试访问第 25 行 C:\xampp\htdocs\twitter\core\classes\follow.php 中 bool 类型值的数组偏移量
- c# - application.System.InvalidOperationException:无法解析类型“Projects.Models.DatabaseContext”的服务
- javascript - Uncaught TypeError: _this.props.data.map is not a function, Map error to render Component
- javascript - 为什么结果与我预期的不同?
- f# - F#:究竟应该如何使用 ToString?
- javascript - 从鼠标单击事件侦听器添加对 Perl CGI 脚本的调用时出现问题
- javascript - React Native 嵌套扁平列表性能不佳
- c++ - 对象生命周期的结束与它何时停止存在之间的关系是什么?
- r - 在R中的表中合并多个保存为xls的html