pair — std::pair

pair — std::pair

std::pair 클래스 템플릿은 두 개의 이기종(heterogeneous) 객체를 하나의 단위로 저장하는 방법을 제공해요. <utility> 헤더에 있어요.

std::pairstd::tuple의 특수한 경우예요 (원소 2개).

출처: cppreference

본문

// <utility> 헤더
template< class T1, class T2 >
struct pair;

사용 예

#include <utility>
#include <string>

std::pair<int, std::string> p(1, "one");
p.first;    // 1
p.second;   // "one"

생성·도우미

#include <utility>

auto a = std::make_pair(1, "hi");      // std::pair<int, const char*>
std::pair<int, int> b{1, 2};           // 브레이스 초기화

// C++17부터 CTAD (템플릿 인자 추론)
std::pair c(3, 4.5);                   // std::pair<int, double>

사용 예 — 맵과 함께

#include <map>

std::map<std::string, int> m;
m.insert({"apple", 1});   // insert는 pair를 받음

for (const auto& kv : m) {
    // kv는 pair — kv.first, kv.second
}

특징

  • first, second 두 멤버로 구성.
  • 비교 연산자(==, <, ...)·std::tie·구조적 바인딩 지원.
std::pair<int,int> a{1,2}, b{1,3};
a < b;   // true (사전순 비교: first, then second)

auto [x, y] = a;   // 구조적 바인딩

std::pair는 두 값을 묶어 반환·저장할 때 가장 기본적인 도구예요. 맵의 키-값, 함수 반환의 다중 값 등에 널리 쓰여요.

더 알아보기 (Learn more)

cppreference