是否有在 C/C++ 中复制数组的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16137953/
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 20:06:03  来源:igfitidea点击:

Is there a function to copy an array in C/C++?

c++carrays

提问by J L

I am a Java programmer learning C/C++. So I know that Java has a function like System.arraycopy(); to copy an array. I was wondering if there is a function in C or C++ to copy an array. I was only able to find implementation to copy an array by using for loop, pointers,etc. Is there a function that I can use to copy an array?

我是一名学习 C/C++ 的 Java 程序员。所以我知道 Java 有一个类似 System.arraycopy(); 的函数。复制一个数组。我想知道 C 或 C++ 中是否有一个函数来复制数组。我只能找到通过使用 for 循环、指针等来复制数组的实现。有没有可以用来复制数组的函数?

采纳答案by taocp

Since C++11, you can copy arrays directly with std::array:

从 C++11 开始,您可以直接使用std::array以下命令复制数组:

std::array<int,4> A = {10,20,30,40};
std::array<int,4> B = A; //copy array A into array B

Here is the documentation about std::array

这是关于std::array的文档

回答by Ed S.

Since you asked for a C++ solution...

既然你要求 C++ 解决方案......

#include <algorithm>
#include <iterator>

const int arr_size = 10;
some_type src[arr_size];
// ...
some_type dest[arr_size];
std::copy(std::begin(src), std::end(src), std::begin(dest));

回答by celtschk

As others have mentioned, in C you would use memcpy. Note however that this does a raw memory copy, so if your data structures have pointer to themselves or to each other, the pointers in the copy will still point to the original objects.

正如其他人提到的,在 C 中你会使用memcpy. 但是请注意,这会进行原始内存复制,因此如果您的数据结构具有指向自身或彼此的指针,则副本中的指针仍将指向原始对象。

In C++ you can also use memcpyif your array members are POD (that is, essentially types which you could also have used unchanged in C), but in general, memcpywill notbe allowed. As others mentioned, the function to use is std::copy.

在C ++中,你也可以使用memcpy,如果你的数组成员是POD(即你也可能用于在C不变,基本类型),但在一般情况下,memcpy不会被允许。正如其他人提到的,要使用的函数是std::copy.

Having said that, in C++ you rarely should use raw arrays. Instead you should either use one of the standard containers (std::vectoris the closest to a built-in array, and also I think the closest to Java arrays — closer than plain C++ arrays, indeed —, but std::dequeor std::listmay be more appropriate in some cases) or, if you use C++11, std::arraywhich is very close to built-in arrays, but with value semantics like other C++ types. All the types I mentioned here can be copied by assignment or copy construction. Moreover, you can "cross-copy" from opne to another (and even from a built-in array) using iterator syntax.

话虽如此,在 C++ 中,您很少应该使用原始数组。相反,您应该使用标准容器之一(std::vector是最接近内置阵列,也是我认为最接近Java数组-比普通的C接近++阵列,确实是- ,但std::deque还是std::list可以在某些情况下更合适)或者,如果您使用 C++11,std::array它非常接近内置数组,但具有与其他 C++ 类型一样的值语义。我在这里提到的所有类型都可以通过赋值或复制构造来复制。此外,您可以使用迭代器语法从 opne 到另一个(甚至从内置数组)“交叉复制”。

This gives an overview of the possibilities (I assume all relevant headers have been included):

这给出了可能性的概述(我假设已包含所有相关标题):

int main()
{
  // This works in C and C++
  int a[] = { 1, 2, 3, 4 };
  int b[4];
  memcpy(b, a, 4*sizeof(int)); // int is a POD

  // This is the preferred method to copy raw arrays in C++ and works with all types that can be copied:
  std::copy(a, a+4, b);

  // In C++11, you can also use this:
  std::copy(std::begin(a), std::end(a), std::begin(b));

  // use of vectors
  std::vector<int> va(a, a+4); // copies the content of a into the vector
  std::vector<int> vb = va;    // vb is a copy of va

  // this initialization is only valid in C++11:
  std::vector<int> vc { 5, 6, 7, 8 }; // note: no equal sign!

  // assign vc to vb (valid in all standardized versions of C++)
  vb = vc;

  //alternative assignment, works also if both container types are different
  vb.assign(vc.begin(), vc.end());

  std::vector<int> vd; // an *empty* vector

  // you also can use std::copy with vectors
  // Since vd is empty, we need a `back_inserter`, to create new elements:
  std::copy(va.begin(), va.end(), std::back_inserter(vd));

  // copy from array a to vector vd:
  // now vd already contains four elements, so this new copy doesn't need to
  // create elements, we just overwrite the existing ones.
  std::copy(a, a+4, vd.begin());

  // C++11 only: Define a `std::array`:
  std::array<int, 4> sa = { 9, 10, 11, 12 };

  // create a copy:
  std::array<int, 4> sb = sa;

  // assign the array:
  sb = sa;
}

回答by Deepu

You can use the memcpy(),

您可以使用memcpy()

void * memcpy ( void * destination, const void * source, size_t num );

memcpy()copies the values of numbytes from the location pointed by sourcedirectly to the memory block pointed by destination.

memcpy()num字节值从 指向的位置source直接复制到指向的内存块destination

If the destinationand sourceoverlap, then you can use memmove().

如果destinationsource重叠,则可以使用memmove().

void * memmove ( void * destination, const void * source, size_t num );

memmove()copies the values of numbytes from the location pointed by sourceto the memory block pointed by destination. Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.

memmove()num字节值从 指向的位置复制到指向source的内存块destination。复制就像使用了中间缓冲区一样进行,允许目标和源重叠。

回答by user541686

Use memcpyin C, std::copyin C++.

memcpy在 Cstd::copy中使用,在 C++ 中使用。

回答by Pete Becker

In C you can use memcpy. In C++ use std::copyfrom the <algorithm>header.

在 C 中,您可以使用memcpy. 在 C++ 中std::copy从头<algorithm>文件使用。

回答by DrumM

I like the answer of Ed S., but this only works for fixed size arrays and not when the arrays are defined as pointers.

我喜欢 Ed S. 的答案,但这仅适用于固定大小的数组,而不适用于将数组定义为指针的情况。

So, the C++ solution where the arrays are defined as pointers:

因此,将数组定义为指针的 C++ 解决方案:

    const int bufferSize = 10;
    char* origArray, newArray;
    std::copy(origArray, origArray + bufferSize, newArray);

Note: No need to deduct buffersizewith 1:

:无需扣除buffersize1:

1) Copies all elements in the range [first, last) starting from first and proceeding to last - 1

1) 复制范围 [first, last) 中的所有元素,从第一个开始并继续到最后一个 - 1

See: https://en.cppreference.com/w/cpp/algorithm/copy

请参阅:https: //en.cppreference.com/w/cpp/algorithm/copy

回答by MORTAL

in C++11 you may use Copy()that works for std containers

在 C++11 中,您可以使用Copy()它适用于 std 容器

template <typename Container1, typename Container2>
auto Copy(Container1& c1, Container2& c2)
    -> decltype(c2.begin())
{
    auto it1 = std::begin(c1);
    auto it2 = std::begin(c2);

    while (it1 != std::end(c1)) {
        *it2++ = *it1++;
    }
    return it2;
}

回答by FaridLU

I give here 2 ways of coping array, for C and C++ language. memcpyand copyboth ar usable on C++ but copyis not usable for C, you have to use memcpyif you are trying to copy array in C.

我在这里给出了 2 种处理数组的方法,适用于 C 和 C++ 语言。memcpycopy都可以在 C++ 上使用,但copy不适用于 C,如果您尝试在 C 中复制数组,则必须使用memcpy

#include <stdio.h>
#include <iostream>
#include <algorithm> // for using copy (library function)
#include <string.h> // for using memcpy (library function)


int main(){

    int arr[] = {1, 1, 2, 2, 3, 3};
    int brr[100];

    int len = sizeof(arr)/sizeof(*arr); // finding size of arr (array)

    std:: copy(arr, arr+len, brr); // which will work on C++ only (you have to use #include <algorithm>
    memcpy(brr, arr, len*(sizeof(int))); // which will work on both C and C++

    for(int i=0; i<len; i++){ // Printing brr (array).
        std:: cout << brr[i] << " ";
    }

    return 0;
}

回答by Ankit Singh

Just include the standard library in your code.

只需在您的代码中包含标准库。

#include<algorithm>

Array size will be denoted as n

数组大小将表示为 n

Your old Array

你的旧阵列

int oldArray[n]={10,20,30,40,50};

Declare New Array in which you have to copy your old array value

声明新数组,您必须在其中复制旧数组值

int newArray[n];

Use this

用这个

copy_n(oldArray,n,newArray);