简体   繁体   English

将元素从一个数组复制到另一个C ++

[英]Copying elements from one array to another c++

I have looked and looked and am still lost on how to copy or get elements from an array and put them into new arrays ( divide and conquer is the goal). 我看了看,现在仍然迷失在如何从数组中复制或获取元素并将它们放入新数组中(分而治之是目标)。

I have an array that generates 100 random numbers. 我有一个生成100个随机数的数组。 I need to split the random numbers into 4 smaller arrays obviously containing 25 elements and not have any duplicates. 我需要将随机数分成4个较小的数组,这些数组显然包含25个元素,并且没有重复项。 I have read about using pointers, but honestly I don't understand why even use a pointer. 我已经读过有关使用指针的内容,但老实说,我什至不明白为什么还要使用指针。 Why do I care about another variables address? 为什么还要关心另一个变量地址?

I don't know how to do this. 我不知道该怎么做。 Here is my code so far: 到目前为止,这是我的代码:

#include <iostream>
#include <time.h>
#include <stdlib.h>

using namespace std;


int main()
{
  // Seed the random number generator

  srand(time(NULL));

  //create an array to store our random numbers in

  int Orignumbers[100]    = {};
  // Arrays for the divide and conquer method
  int NumbersA   [25]     = {};
  int NumbersB   [25]     = {};
  int NumbersC   [25]     = {};
  int NumbersD   [25]     = {};


  //Generate the random numbers
  for(int i =0; i < 100; i++)
  {
    int SomeRandomNumber = rand() % 100 + 1;

  // Throw random number into the array

  Orignumbers[i] = SomeRandomNumber;

  }

//  for(int i = 0; i < ) started the for loop for the other arrays, this is where I am stuck!!

  // Print out the random numbers
  for(int i = 0; i < 100; i++)
  {
    cout << Orignumbers[i] << " , ";
  }

}

"divide and conquer" is rather easy; “分而治之”相当容易; when copying into NumbersA and so forth, you just have to access your Originnumbers with a proper offset, ie 0 , 25 , 50 , and 75 : 复制到当NumbersA等等,你只需要访问您的Originnumbers以适当的偏移,即02550 ,以及75

for(int i = 0; i < 25; i++) {
    NumbersA[i] = Orignumbers[i];
    NumbersB[i] = Orignumbers[i+25];
    NumbersC[i] = Orignumbers[i+50];
    NumbersD[i] = Orignumbers[i+75];
}

The thing about "no duplicates" is a little bit more tricky. 关于“无重复”的问题有些棘手。 Generating a random sequence of unique numbers is usually solved through "shuffling". 通常通过“改组”来解决生成唯一编号的随机序列的问题。 Standard library provides functions for that: 标准库提供了以下功能:

#include <random>
#include <algorithm>
#include <iterator>
#include <vector>

int main()
{
    std::random_device rd;
    std::mt19937 g(rd());

    int Orignumbers[100];

    //Generate the random numbers without duplicates
    for(int i =0; i < 100; i++) {
        Orignumbers[i] = i+1;
    }
    std::shuffle(Orignumbers, Orignumbers+100, g);

    // Arrays for the divide and conquer method
    int NumbersA   [25]     = {};
    int NumbersB   [25]     = {};
    int NumbersC   [25]     = {};
    int NumbersD   [25]     = {};


    for(int i = 0; i < 25; i++) {
        NumbersA[i] = Orignumbers[i];
        NumbersB[i] = Orignumbers[i+25];
        NumbersC[i] = Orignumbers[i+50];
        NumbersD[i] = Orignumbers[i+75];
    }

    // Print out the random numbers
    for(int i = 0; i < 100; i++)
    {
        cout << Orignumbers[i] << " , ";
    }

}

As you tagged your question with C++ then forget about old-fashion arrays, let's do it C++ style. 当您使用C ++标记问题时,然后忘记了老式数组,就让我们使用C ++样式吧。 You want to split your array into 4 arrays and they should not have duplicate numbers , so you can't have a number 5 times in your original array, because then surely one of your 4 arrays will have a duplicate one, So here is the way I propose to do it : 您想将数组拆分为4个数组,并且它们不应该重复的数字 ,因此您不能在原始数组中重复 5次,因为这样一来,您肯定会在4个数组中有一个重复,所以这是我建议这样做的方式:

#include <set>
#include <ctime>
#include <vector>

int main() {
    std::multiset<int> allNums;
    std::srand(unsigned(std::time(0)));

    for (int i = 0; i < 100; ++i) {
        int SomeRandomNumber = std::rand() % 100 + 1;
        if (allNums.count(SomeRandomNumber) < 4) {
            allNums.insert(SomeRandomNumber);
        }
        else {
            --i;
        }
    }
    std::vector<int> vOne, vTwo, vThree, vFour;
    for (auto iter = allNums.begin(); iter != allNums.end(); ++iter) {
        vOne.push_back(*iter);
        ++iter;
        vTwo.push_back(*iter);
        ++iter;
        vThree.push_back(*iter);
        ++iter;
        vFour.push_back(*iter);
    }
    system("pause");
    return 0;
}

EDIT : As you mentioned in the comments, you just want to find a number in an array, so how about this : 编辑:正如您在评论中提到的那样,您只想在数组中找到一个数字,那么如何做:

for (int i = 0; i < 100; ++i) {
    if (origArray[i] == magicNumber) {
        cout << "magicNumber founded in index " << i << "of origArray";
    }
}

Problem: 问题:

The program can't be guaranteed to have no duplicate value as the rand() function can generate any random sequence and that may include the decimal value of 99 for 99 times though probability is very low but chances are . 不能保证程序没有重复值,因为rand()函数可以生成任何随机序列,并且可能包含99的十进制值(99倍),尽管概率非常低,但机会是
Example: 例:

for(loop=0; loop<9; loop++) 
printf("%d", Rand()%10);

If looped for 10 times, it may result some values like: 如果循环十次,则可能会产生一些值,例如:

  Output: 6,1,1,1,2,9,1,3,6,9
  Compiled Successfully:

Hence, no certainity that values won't repeat 因此,无法确定价值观不会重复

Possibly Solution: 可能的解决方案:

There could be a solution where you can place the values in OriginalArray and compare the rand() generate values against the OriginalArray values. 可能存在一种解决方案,您可以将值放在OriginalArray然后将rand()生成的值与OriginalArray值进行比较。 For first iteration of loop, you can directly assign value to OriginalArray then from 2nd iteration of loop you've to compare rand() value against OriginalArray but insertion time consumption may be higher than O(N N ) as rand() function may repeat values. 对于循环的第一次迭代,您可以直接将值分配给OriginalArray然后从循环的第二个迭代中,您必须将rand()值与OriginalArray进行比较,但由于rand()函数可能重复,因此插入时间消耗可能会比O(N N高价值观。

Possibly Solution: 可能的解决方案:

 #include <iostream>
 #include <time.h>
 #include <stdlib.h>
 using namespace std;
 int main()
 {
   int Orignumbers[100] ;

  int NumbersA [25] ,
    NumbersB [25] , 
    NumbersC [25] , 
    NumbersD [25] ;
    srand(time(NULL));

   for(int i =0; i < 100; i++){
    Orignumbers[i] = rand() % 100+1; 
   for(int loop=0; loop<i; loop++) {
       if(Orignumber[loop] == Orignumber[i] ) {
           i--;
           break;
        }
     }
  }

    //Placing in four different arrays thats maybe needed.
    for(int i = 0; i <25; i++ ) {
    NumbersA[i] = Orignumbers[i];
    NumbersB[i] = Orignumbers[i+25];
    NumbersC[i] = Orignumbers[i+50];
    NumbersD[i] = Orignumbers[i+75];
    } 

    for(int i = 0; i < 99; i++)
    cout << Orignumbers[i] << " , ";
    }

On some situations, even on C++, the use of arrays might be preferable than vectors, for example, when dealing with multidimensional arrays (2D, 3D, etc) that needs to be continuous and ordered on the memory. 在某些情况下,甚至在C ++上,使用数组也可能比向量更可取,例如,在处理需要连续且在内存中排序的多维数组(2D,3D等)时。 (eg later access by other applications or faster exporting to file using formats such as HDF5.) (例如,以后可以被其他应用程序访问,或者使用HDF5等格式更快地导出到文件。)

Like Jesper pointed out, you may use Copy and I would add MemCopy to copy the content of an array or memory block into another. 就像Je​​sper指出的那样,您可以使用Copy ,我可以添加MemCopy来将数组或内存块的内容复制到另一个数组或内存块中。

Don't underestimate the importance of pointers, they may solve your problem without the need doing any copy. 不要低估指针的重要性,它们可以解决您的问题而无需执行任何复制。 A bit like Stephan solution but without the need of the index variable "i", just having the pointers initialized at different places on the array. 有点类似于Stephan解决方案,但不需要索引变量“ i”,只是将指针初始化在数组的不同位置。 For a very large number of elements, such strategy will save some relevant processing time. 对于大量元素,这种策略将节省一些相关的处理时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM