본문 바로가기
C++/[AssortRock] C++ 기초 다지기

CPP_1. AssortRock 15일차 오프라인 수업_220927

by 헛둘이 2022. 9. 28.
std::pair 구현
  • pair는 map을 구성하는 요소
  • map과 pair는 항상 같이 쓰임

 

namespace ya
{
	template<typename T1, typename T2>
	class pair
	{
	public:


	public:
		T1 first;
		T2 second;
	};
}
  • pair의 기본 모양
  • 템플릿으로 타입 2개를 받아서 그 타입에 대응하는 값의 쌍으로 만들어짐
  • 외부에서 first와 second에 접근할 수 있으므로 데이터를 public으로 뺌

 

pair()
	: first(T1())
	, second(T2())
{}

// 생성자
pair(const T1& f, const T2& s)
	: first(f)
	, second(s)
{}

// 이동 생성자
pair(T1&& f, T2&& s)
	: first(f)
	, second(s)
{}
  • 기본 생성자와 이동 생성자
  • 이동 생성자는 값의 복사가 일어나지 않아서 메모리를 효율적으로 사용할 수 있다.
  • 원본을 넘겨 받는 개념을 초월해서 그 메모리 자체의 소유권을 갖는 것 

 

template<typename U1, typename U2>
pair(const pair<U1, U2>& other)
	: first(other.first)
	, second(other.second)
{}

template<typename U1, typename U2>
pair(pair<U1, U2>&& other)
	: first(std::forward(other.first))
	, second(std::forward(other.second))
{}
  • pair 간의 복사,이동이 발생할 때의 생성자
  • std::forward는 인자 값이 lvalue면 lvalue로 넘겨주고 rvalue로 오면 rvalue로 넘겨줌
  • other가 rvalue로 넘어오면 reference collapsing 규칙에 의해 rvalue가 된다.

 

pair& operator=(const pair& other)
{
	first = other.first;
	second = other.second;

	return *this;
}

pair& operator=(pair&& other)
{
	first = std::move(other.first);
	second = std::move(other.second);

	return *this;
}
  • 복사 대입, 이동 대입 연산자 재정의
  • 이동 대입 연산자에선 move를 통해 first, second에 넣어주는 것을 볼 수 있음
  • move로 넣어주면 first와 second에 구현되어 있는 이동 대입 연산자가 불리므로 성능 향상의 이점이 있음

 

 

bool operator==(const pair& other) const
{
	return ((first == other.first) &&
		(second == other.second));
}

bool operator!=(const pair& other) const
{
	return !(*this == other);
}

bool operator<(const pair& other) const
{
	if (first < other.first)
		return true;

	else if (first == other.first)
	{
		if (second < other.second)
			return true;

		else
			return false;
	}

	else
		return false;
}

bool operator<=(const pair& other) const
{
	if (first <= other.first)
		return true;

	else
		return false;
}

bool operator>(const pair& other) const
{
	if (first > other.first)
		return true;

	else if (first == other.first)
	{
		if (second > other.second)
			return true;

		else
			return false;
	}

	else
		return false;
}

bool operator>=(const pair& other) const
{
	if (first >= other.first)
		return true;

	else
		return false;
}
  • 숙제로 나온 비교 연산자들
  • std::pair의 특성 상 first끼리 먼저 비교하고 같다면 second를 비교하는 식이므로
  • 이 점을 적용해서 제출했다.
  • >, < 비교 구문에서  else if (first == other.first)인 경우 second와 other.second를 비교하는데
  • 여기서 true가 아니라면 같더나 작다 혹은 크다는 의미이므로 둘 다 false이므로 false를 반환한다.

댓글