๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’Ž/C++

[C++] ๋ฐฐ์—ด๋ณต์‚ฌ memcpy, copy

by dar0m! 2020. 3. 23.

memcpy

#include <string.h>  // C++ ์—์„œ๋Š” <cstring>

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

์˜ˆ์ œ

memcpy(arr, tarr, sizeof(arr));

 

copy

#include <algorithm>

copy(initArray, initArray + n, v.begin()); // initArray๋‚ด์šฉ์„ n๋งŒํผ v์— ๋ณต์‚ฌ

copy(v.begin(), v.end(), v2.begin()); // v์˜ ๋‚ด์šฉ์„ v2์— ๋ณต์‚ฌ

 

์ƒ์„ธ

template<class InputIterator, class OutputIterator>
  OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
  while (first!=last) {
    *result = *first;
    ++result; ++first;
  }
  return result;
}

์˜ˆ์ œ

#include <iostream>
#include <algorithm>    // copy
#include <vector>       // vector
using namespace std;
int n = 7;
int main() {
	vector<int> v(n);
	int initArray[] = { 10,20,30,40,50,60,70 };

	copy(initArray, initArray + n, v.begin());

	cout << "v contains:";
	for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
		printf("%d ", *it);
	
	// vector<int> v2; ํฌ๊ธฐ๊ฐ€ ์—†์–ด์„œ ๋ณต์‚ฌ ์‹คํŒจ
	vector<int> v2;
	v2.resize(n);
	copy(v.begin(), v.end(), v2.begin());

	vector<int>::iterator iter = v2.begin();
	printf("\n%d", iter[3]);

	return 0;
}

์‹คํ–‰๊ฒฐ๊ณผ

 

๋Œ“๊ธ€