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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11102029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:51:14  来源:igfitidea点击:

How can I copy a part of an array to another array in C++?

c++

提问by

This is the same question asked in C# but i need for C++

这是在 C# 中提出的相同问题,但我需要 C++

How can I copy a part of an array to another array?

如何将数组的一部分复制到另一个数组?

Consider I'm having

考虑我有

    int[] a = {1,2,3,4,5};

Now if I give the start index and end index of the array a it should get copied to another array.

现在,如果我给出数组 a 的开始索引和结束索引,它应该被复制到另一个数组。

Like if I give start index as 1 and end index as 3, the elements 2, 3, 4 should get copied in the new array.

就像我将开始索引设置为 1 并将结束索引设置为 3 一样,元素 2、3、4 应该被复制到新数组中。

In C# it is done as following

在 C# 中,它是按如下方式完成的

     int[] b = new int[3];
    Array.Copy(a, 1, b, 0, 3);

Is there any simple way like this to do the same task in C++?

有没有像这样的简单方法可以在 C++ 中完成相同的任务?

回答by

Yes, use std::copy:

是的,使用std::copy

std::copy(a + src_begin_index,
          a + src_begin_index + elements_to_copy,
          b + dest_begin_index);

The equivalent of your C# example would be:

相当于您的 C# 示例将是:

std::copy(a + 1, a + 4, b);

回答by Mike Seymour

Assuming you want a dynamically-allocated array as in the C# example, the simplest way is:

假设您想要一个动态分配的数组,如 C# 示例中所示,最简单的方法是:

std::vector<int> b(a.begin() + 1, a.begin() + 4);

This also has the advantage that it will automatically release the allocated memory when it's destroyed; if you use newyourself, then you'll also need to use deleteto avoid memory leaks.

这还有一个好处,就是在销毁时会自动释放分配的内存;如果您new自己使用,那么您还需要使用delete以避免内存泄漏。

回答by Richard J. Ross III

There is the Cmemcpycommand, which you can use like this:

有一个Cmemcpy命令,你可以这样使用:

memcpy(destinationArray, sourceArray, sizeof(*destinationArray) * elementsToCopy);

There is also std::copy, which is a more C++way of doing it:

还有std::copy,这是一种更多的C++方法:

std::copy(source, source + elementsInSource, destination);

Note that neither of these functions check to make sure that enough memory has been allocated, so use at your own risk!

请注意,这些函数都不会检查以确保已分配足够的内存,因此使用风险自负!

回答by jpalecek

Yes, using st standard library algorithm copy:

是的,使用 st 标准库算法copy

#include <algorithm>

int main()
{
  int array[5] = { 1,2,3,4,5 }; // note: no int[] array
  int *b = new int[3];
  std::copy(array+1, array+4, b); 
  // copies elements 1 (inclusive) to 4 (exclusive), ie. values 2,3,4
}

回答by Some programmer dude

For simple C-style arrays you can use memcpy:

对于简单的 C 样式数组,您可以使用memcpy

memcpy(b, &a[1], sizeof(int) * 3);

This line copies sizeof(int) * 3bytes (i.e. 12 bytes) from index 1 of a, with bas a destination.

此行sizeof(int) * 3从 的索引 1复制字节(即 12 个字节)a,并将其b作为目的地。