본문 바로가기

C++/기본 문법

<C++> fill과 memset, memcpy

std::fill 함수 원형(배열 초기화, 값 채우기 가능)


template< class ForwardIt, class T >
void fill(ForwardIt first, ForwardIt last, const T& value)
{
    for (; first != last; ++first) {
        *first = value;
    }
}

 

std::memset 함수 원형(배열 초기화)


void* memset( void* dest, int ch, std::size_t count );

 

std::memcpy 함수 원형(배열 값 복사 가능)


void* memcpy( void* dest, const void* src, std::size_t count );

 

 

활용 코드


#include<bits/stdc++.h>
using namespace std;
vector<int> v(5, 10); // 5개의 10값으로 초기화 
vector<int> temp(5, 10); 

void PrintIntVector(const vector<int>& src)
{
	for(int i : src)
	{
		cout << i << " ";
	}
	cout << endl;	
}

int main()
{
	// fill을 이용한 초기화 
	fill(v.begin(), v.end(), 0);
	PrintIntVector(v);
	
	// fill을 이용한 값 채우기
	fill(v.begin(), v.begin() + 10, 10); 
	PrintIntVector(v);
	
	// memset를 이용한 초기화 
	memset(v.data(), 0, sizeof(v)); 
	PrintIntVector(v);
	
	// memcpy를 이용한 값 복사(배열을 배열로 복사) 
	memcpy(v.data(), temp.data(), sizeof(temp)); 
	PrintIntVector(v);
	
	/*
	0 0 0 0 0
	10 10 10 10 10
	0 0 0 0 0
	10 10 10 10 10
	*/
	 
	
	return 0;
}
 

 

함수 원형 출처 : https://en.cppreference.com/

 

std::memset - cppreference.com

Converts the value ch to unsigned char and copies it into each of the first count characters of the object pointed to by dest. If the object is a potentially-overlapping subobject or is not TriviallyCopyable (e.g., scalar, C-compatible struct, or an array

en.cppreference.com

 

'C++ > 기본 문법' 카테고리의 다른 글

Lvalue와 Rvalue 차이  (0) 2022.09.28
<C++> string reverse(), substr()  (0) 2022.07.20
<C++> 정적 배열(Array)  (0) 2022.04.12
<C++> vector  (0) 2022.04.12
<C++> sort  (0) 2022.04.12