Development Tip

C / C ++에서 배열을 복사하는 기능이 있습니까?

yourdevel 2020. 10. 30. 21:10
반응형

C / C ++에서 배열을 복사하는 기능이 있습니까?


저는 C / C ++를 배우는 Java 프로그래머입니다. 그래서 Java에는 System.arraycopy ();와 같은 기능이 있다는 것을 알고 있습니다. 배열을 복사합니다. 배열을 복사하는 함수가 C 또는 C ++에 있는지 궁금합니다. for 루프, 포인터 등을 사용하여 배열을 복사하는 구현 만 찾을 수있었습니다. 배열을 복사하는 데 사용할 수있는 함수가 있습니까?


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

다음은 std :: array 에 대한 문서입니다.


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

다른 사람들이 언급했듯이 C에서는 memcpy. 그러나 이것은 원시 메모리 복사를 수행하므로 데이터 구조에 자체 또는 서로에 대한 포인터가있는 경우 복사본의 포인터는 여전히 원래 개체를 가리 킵니다.

C ++에서 당신은 또한 사용할 수있는 memcpy배열 구성원이, (당신은 또한 C에서 변경 사용할 수도 본질적 유형이다) 그러나 일반적으로, POD하면 memcpy됩니다 되지 허용합니다. 다른 사람들이 언급했듯이 사용할 기능은 std::copy.

하지만 C ++에서는 원시 배열을 거의 사용하지 않아야합니다. 대신 당신도 표준 컨테이너 중 하나를 사용해야합니다 ( std::vector있는 배열 내장, 또한 내가 자바 배열에 가까운 생각에 가장 가까운 - 가까운 일반 C보다 ++ 배열, 참 -하지만, std::deque또는 std::list어떤 경우에는 더 적합 할 수 있음) 또는 std::array내장 배열에 매우 가깝지만 다른 C ++ 유형과 같은 값 의미를 갖는 C ++ 11을 사용하는 경우 . 여기서 언급 한 모든 유형은 할당 또는 복사 구성으로 복사 할 수 있습니다. 또한 반복자 구문을 사용하여 opne에서 다른 것으로 (및 내장 배열에서도) "교차 복사"할 수 있습니다.

이것은 가능성에 대한 개요를 제공합니다 (모든 관련 헤더가 포함되었다고 가정합니다).

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

당신은을 사용할 수 있습니다 memcpy(),

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

memcpy() copies the values of num bytes from the location pointed by source directly to the memory block pointed by destination.

If the destination and source overlap, then you can use memmove().

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

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


Use memcpy in C, std::copy in C++.


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


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

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

I give here 2 ways of coping array, for C and C++ language. memcpy and copy both ar usable on C++ but copy is not usable for C, you have to use memcpy if you are trying to copy array in C.

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

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

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

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

Note: No need to deduct buffersize with 1:

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

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


Firstly, because you are switching to C++, vector is recommended to be used instead of traditional array. Besides, to copy an array or vector, std::copy is the best choice for you.

Visit this page to get how to use copy function: http://en.cppreference.com/w/cpp/algorithm/copy

Example:

std::vector<int> source_vector;
source_vector.push_back(1);
source_vector.push_back(2);
source_vector.push_back(3);
std::vector<int> dest_vector(source_vector.size());
std::copy(source_vector.begin(), source_vector.end(), dest_vector.begin());

Just include the standard library in your code.

#include<algorithm>

Array size will be denoted as 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);

참고URL : https://stackoverflow.com/questions/16137953/is-there-a-function-to-copy-an-array-in-c-c

반응형