1. memcpy
void* memcpy(void* destination, const void* source, std::size_t count)
std::memcpy - cppreference.com
void* memcpy( void* dest, const void* src, std::size_t count ); Copies count bytes from the object pointed to by src to the object pointed to by dest. Both objects are reinterpreted as arrays of unsigned char. If the objects overlap, the behavior is undefi
en.cppreference.com
- #include <cstring> 헤더에 정의되어 있다.
- source 가 가리키는 객체에서 count (바이트) 만큼 destination 이 가리키는 객체로 복사한다.
- 두 객체는 모두 unsigned char array 로 재해석한다.
- destination 또는 source 가 유효하지 않거나 nullptr 인 경우 count 가 0이어도 undefined behavior
- 두 객체가 겹치는 경우 undefined behavior
- 메모리에서 메모리로 복사하는 라이브러리 함수 중 가장 빠르다고 볼 수 있다.
간단한 예시)
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char src1[] = "onetwothree";
char dest1[4];
memcpy(dest1, src1, sizeof(dest));
for (char c : dest1)
cout << "'" << c << "' ";
cout << "\n";
}
출력값: 'o' 'n' 'e' 't'
2. copy / copy_if
(output iterator) copy((input iterator) first, (input iterator) last, (output iterator) dest_first)
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
- <algorithm> 헤더에 정의되어 있다.
- [first, last) 범위의 원소를 순서대로 dest_first 로 시작하는 범위에 복사한다.
- dest_first 가 [first, last) 범위 안에 있는 경우 undefined behavior
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> from_vector(10);
int val = 0;
for (vector<int>::iterator it = from_vector.begin(); it != from_vector.end(); it++) {
*it = val;
val++;
}
vector<int> to_vector(from_vector.size());
copy(from_vector.begin(), from_vector.end(), to_vector.begin());
for (vector<int>::iterator it = to_vector.begin(); it != to_vector.end(); it++) {
cout << *it << " ";
}
}
+ copy_if(first, last, dest_first, predicate)
- predicate 이 true 를 반환하는 원소만 복사한다.
- 순서는 보존된다.
+ copy()와 copy_if() 모두 ExecutionPolicy 를 첫 인자로 추가하여 호출하면 policy 에 따라 복사를 수행한다.
참고) 누군가 memcpy, copy, for loop 으로 복사하는 것 각각의 속도를 비교하였다 ㅎㅎ
https://blog.naver.com/cloudcie/220237997398
memcpy VS for loop VS std::copy, 누가 더 빠를까?
<1. 테스트 기기 사양>Processor Intel(R) Core(TM) i5-3210M CPU @...
blog.naver.com
추가로 알게된 신기한 함수..
<algorithm> ... void iota(forward_iterator first, forward_iterator last, (type) value)
**하지만... C++ 20 이상에서 사용 가능
- [first, last)의 범위를 value에서 시작해 type의 단위만큼 증가하는 원소로 채운다.
std::iota - cppreference.com
template< class ForwardIt, class T > void iota( ForwardIt first, ForwardIt last, T value ); (since C++11) (constexpr since C++20) Fills the range [first, last) with sequentially increasing values, starting with value and repetitively evaluating ++value. E
en.cppreference.com