IT이야기

C/C++에 어레이를 복사하는 기능이 있는가?

cyworld 2022. 5. 10. 22:27
반응형

C/C++에 어레이를 복사하는 기능이 있는가?

나는 C/C++를 배우는 자바 프로그래머야.그래서 나는 자바에 System과 같은 기능이 있다는 것을 알고 있다.배열복사본(); 배열을 복사하는 방법.C나 C++에 배열을 복사하는 기능이 있는지 궁금했어.루프, 포인터 등을 사용하여 어레이를 복사하는 구현을 찾을 수 있었다.어레이를 복사하는 데 사용할 수 있는 기능이 있는가?

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++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에서 당신은memcpy그러나 이것은 원시 메모리 복사를 하므로 데이터 구조가 자신이나 서로에 대한 포인터를 가지고 있더라도 복사본의 포인터는 여전히 원래 개체를 가리킨다.

C++에서는 사용할 수도 있다.memcpy할 수 인 경우, 어어즈 이 멤버십가 POD(도도, CETORODOWDOWDORDOWDORDOWDORDOWDORDOWDORDOWDORD)인 경우, 일요일날로.memcpy허락되지 않을 것이다.다른 사람들이 언급했듯이, 사용할 기능은std::copy.

그렇긴 하지만 C++에서는 원시 배열을 사용하는 일이 거의 없다.std::vector기본 제공 어레이에 가장 가깝고, Java 어레이에 가장 가까우며, 일반 C++ 어레이보다 더 가깝지만,std::deque또는std::list경우에 따라서는 더 적합할 수도 있다) 또는 C++11을 사용하면std::array이는 내장 어레이에 매우 가깝지만 다른 C++ 유형과 같은 가치 의미 체계를 갖추고 있다.내가 여기서 말한 모든 타입은 배정이나 복사 공사로 복사할 수 있다.또한 반복기 구문을 사용하여 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;
}

나는 Ed S의 대답을 좋아하지만, 이것은 고정된 크기 배열에만 작용하며, 배열들이 포인터로 정의될 때는 그렇지 않다.

따라서 어레이를 포인터로 정의하는 C++ 솔루션:

#include<algorithm>
...
const int bufferSize = 10;
char* origArray, newArray;
std::copy(origArray, origArray + bufferSize, newArray);

참고: 차감할 필요 없음buffersize1:

  1. 첫 번째 요소부터 마지막 요소까지 [첫 번째, 마지막] 범위의 모든 요소 복사 - 1

https://en.cppreference.com/w/cpp/algorithm/copy을 참조하십시오.

사용하다memcpy주식회사std::copyC++로

코드에 표준 라이브러리를 포함하십시오.

#include<algorithm>

배열 크기는 다음과 같이 표시됨n

이전 어레이

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

이전 어레이 값을 복사해야 하는 새 어레이 선언

int newArray[n];

사용

copy_n(oldArray,n,newArray);

C에서 당신은 사용할 수 있다.memcpy. C++ 사용 시std::copy처음부터<algorithm>머리글

다음을 시도해 보십시오.

  1. 빈 배열을 생성하십시오.
  2. 요소를 삽입하십시오.
  3. 같은 크기의 빈 배열을 중복으로 만드십시오.
  4. 시작:i=0길게
    5. newarray[i]=oldarray[i](C++의 경우에만 해당)

C++ 프로그램

#include<iostream>
using namespace std;
int main()
{
        int initA[100],finA[100],i,size;
        cout<<"Input the size of the array : ";
        cin>>size;
        cout<<"Input the elements of the first array";
        for(i=0;i<size;i++)
        {
               cin>>initA[i];
        }
        for(i=0;i<size;i++)
        {
             finA[i]=initA[i];
        }
        cout<<"The final array is\n";
        for(i=0;i<size;i++)
               cout<<finA[i]<<" ";
        return 0;
}

첫째, C++로 전환하기 때문에 기존의 배열 대신 벡터를 사용하는 것이 좋다.게다가 배열이나 벡터를 복사하려면std::copy널 위한 최선의 선택이야

복사 기능 사용 방법을 보려면 이 페이지를 방문하십시오. http://en.cppreference.com/w/cpp/algorithm/copy

예:

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

당신은 그것을 사용할 수 있다.memcpy(),

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

memcpy()의 가치를 모방하다num지정한 위치로부터 바이트 수source바로 기억 블록으로destination.

만약destination그리고source겹쳐서 사용하면memmove().

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

memmove()의 가치를 모방하다num지정한 위치로부터 바이트 수source에 의해 지적된 기억 블록까지.destination. 복사는 중간 버퍼를 사용한 것처럼 이루어져서 목적지와 소스가 겹칠 수 있다.

나는 여기에 C와 C++ 언어의 2가지 대응 방법을 제시한다.c++에서는 memcpy와 copy ar를 모두 사용할 수 있지만 c에서는 copy를 사용할 수 없다. 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;
}

C++11에서는 다음을 사용하십시오.Copy()표준 컨테이너에 사용할 수 있는

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

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

반응형