๐Ÿ“ Coding Test Study/C++

[C++][์ž๋ฃŒ๊ตฌ์กฐ] 1์ฐจ์›/2์ฐจ์› ๋ฐฐ์—ด ๋ณต์‚ฌ, ๋ฒกํ„ฐ ๋ณต์‚ฌ

ibelieveinme 2025. 3. 3. 13:59
728x90

 

C++ ์—์„œ ์ œ๊ณตํ•˜๋Š” copy ๋ฌธ์€ copy, copy_if ๊ฐ€ ์žˆ๊ณ  copy_if ๋ฅผ ์“ฐ๋ฉด ์กฐ๊ฑด๋ฌธ์„ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

  • ํ—ค๋”

#include <algorithm>

 

  • ํ•จ์ˆ˜

copy(์‹œ์ž‘ ์ง€์ , ๋ ์ง€์ , ๋ณต์‚ฌ๋  ๋ณ€์ˆ˜ ์‹œ์ž‘์ง€์ );

copy_if( ์‹œ์ž‘ ์ง€์ , ๋ ์ง€์ , ๋ณต์‚ฌ๋  ๋ณ€์ˆ˜ ์‹œ์ž‘์ง€์ , ์กฐ๊ฑด);

 

  • ์˜ˆ์‹œ

1) 1์ฐจ์› ๋ฐฐ์—ด ๋ณต์‚ฌ

#include <iostream>
#include <algorithm>

int main(){
    int arr[4] = {1, 2, 3, 4};
    int copiedArr[4] = {0, };
    
    copy(arr, arr+4, copiedArr);
    
    return 0;
}

 

2) 2์ฐจ์› ๋ฐฐ์—ด ๋ณต์‚ฌ

#include <iostream>
#include <algorithm>

int main(){
    int arr[2][4] = {{0,-1}, {0,1}, {-1,0}, {1,0}};
    int copiedArr[2][4];
    
    copy(&arr[0][0], &arr[0][0]+(2*4), &copiedArr[0][0]);
    
    return 0;
}

 

3) ๋ฒกํ„ฐ๋ณต์‚ฌ

copy(v.begin(), v.end(), v_copy.begin());

* ์ฐธ๊ณ ์ž๋ฃŒ: https://en.cppreference.com/w/cpp/algorithm/copy

 

std::copy, std::copy_if - cppreference.com

template< class InputIt, class OutputIt > OutputIt copy( InputIt first, InputIt last,                OutputIt d_first ); (1) (constexpr since C++20) template< class ExecutionPolicy,           class ForwardIt1, class ForwardIt2 > ForwardIt2 cop

en.cppreference.com

 

728x90