首页 > 解决方案 > 关于 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){

}

标签: c++

解决方案


我没有完全理解这个问题,但如果我是对的,你想创建一个函数,在现有数组的每个元素之后插入一个元素。这可能是您正在寻找的。如果不是,请重新表述问题。

    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;
    }

推荐阅读