如何将此INT数组的一部分复制到C 中的另一个数组

How would I copy a part of this int array into another in C++?

本文关键字:数组 另一个 复制 一部分 INT      更新时间:2023-10-16

这就是我到目前为止所拥有的:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    int size;
    int sizeCopy= 0;
    int *array;
    cin >> size;
    cout << endl;
    cin >> sizeCopy;
    array = new int [size];
    int i = 0;
    int counter = 1;
    while(i<size)
    {
        array[i] = counter;
        ++counter;
        ++i;
    }
    cout << "The array contains: ";
    for(i=0; i<size; i++)
    {
        cout << array[i] << ", ";
    }
    cout << "n";
    return 0;
}

到目前为止,我创建了一个程序,该程序将要求使用数组大小的用户输入,以及在新数组中将复制数组的数量的大小(这是Sizecopy)。

我设法创建了第一个数组,我希望它是这样的:如果用户输入为3,则数组将包含1、2、3。i用户输入为10,数组将包含1、2、3、4、5、6、7、8、9、10。

这似乎很好。现在,我想将我的一部分int阵列复制到另一个阵列,但比这要复杂得多。假设第一个数组的用户输入(大小)为10,而Sizecopy(您想要复制到第二个数组中的元素有多少个元素)为2,那么我希望第二个数组为:1,2。不过还没有结束,我希望整个数组在一段时间后将整个数组复制到第二个数组中。我想要这样的东西:

  • 1,2
  • 收到第1部分
  • 1,2,3,4
  • 收到第2部分
  • 1、2、3、4、5、6
  • 收到第3部分
  • 1、2、3、4、5、6、7、8
  • 收到第4部分
  • 1、2、3、4、5、6、7、8、9、10
  • 收到第5部分

计划中包含"收到的部分"。然后将完成。

如果第一个数组大小的用户为4,而sizecopy是2,那么我想要这样的东西:

  • 1,2
  • 收到第1部分
  • 1,2,3,4
  • 收到第2部分

我可以在如何完成此操作方面获得一些帮助吗?我认为我可以管理如何将整个数组复制到另一个数组,或者至少一部分。但是,我想做什么?我以为我需要循环,但我不知道更多。

tl; dr我要回答标题中的问题。

与构造函数一起使用 std::vector

template< class InputIt >
vector( InputIt first, InputIt last, 
    const Allocator& alloc = Allocator() );

std::copy

我不喜欢C 方法(sTD :: copy) - 我宁愿使用memcpy()memmove()。我在 _control_ </sarcasm>

中感到更多