티스토리 뷰

공부한거/C++

#include<utility>

tl;dr 2024. 11. 22. 15:28

#include <utility>는 C++ 표준 라이브러리에서 유틸리티 함수와 클래스를 제공하는 헤더 파일입니다. 주로 페어(pair), 이동 시멘틱(move semantics), 그리고 다양한 도구를 제공합니다.


1. 주요 기능

A. std::pair

  • 두 개의 값을 함께 저장하는 템플릿 클래스.
  • 서로 다른 타입의 데이터를 하나로 묶는 데 유용합니다.
  • 사용 예:
     
#include <iostream>
#include <utility>

int main() {
    std::pair<int, std::string> p = {1, "Hello"};
    std::cout << p.first << ", " << p.second << std::endl;  // 출력: 1, Hello
    return 0;
}

B. std::make_pair

  • std::pair를 생성하는 헬퍼 함수.
  • 타입을 명시하지 않아도 자동으로 유추됩니다.
#include <iostream>
#include <utility>

int main() {
    auto p = std::make_pair(42, "World");
    std::cout << p.first << ", " << p.second << std::endl;  
}

C. std::move

  • 객체의 소유권을 이동시키는 함수.
  • 복사보다 효율적인 **이동 시멘틱(move semantics)**을 구현할 때 사용.
  • 사용 예:
#include <iostream>
#include <utility>
#include <string>

int main() {
    std::string str = "Hello";
    std::string movedStr = std::move(str);

    std::cout << "movedStr: " << movedStr << std::endl;  // 출력: Hello
    std::cout << "str: " << str << std::endl;            // 출력: (빈 문자열)
    return 0;
}

D. std::swap

  • 두 변수의 값을 교환하는 함수.
  • 사용자 정의 타입에서도 효율적으로 작동.
#include <iostream>
#include <utility>

int main() {
    int a = 10, b = 20;
    std::swap(a, b);

    std::cout << "a: " << a << ", b: " << b << std::endl;  // 출력: a: 20, b: 10
    return 0;
}

E. std::forward

  • **완벽한 전달(perfect forwarding)**을 구현할 때 사용.
  • 함수 템플릿에서 전달된 인수의 값을 유지.
  • 사용 예:
#include <iostream>
#include <utility>

void print(int& x) {
    std::cout << "Lvalue: " << x << std::endl;
}

void print(int&& x) {
    std::cout << "Rvalue: " << x << std::endl;
}

template <typename T>
void forwardPrint(T&& val) {
    print(std::forward<T>(val));  // 전달된 값의 속성을 유지
}

int main() {
    int num = 10;
    forwardPrint(num);          // 출력: Lvalue: 10
    forwardPrint(20);           // 출력: Rvalue: 20
    return 0;
}

F. std::tie

  • std::tuple이나 std::pair의 값을 언패킹(해체)하는 데 사용.
  • 사용 예:
#include <iostream>
#include <utility>

int main() {
    std::pair<int, std::string> p = {1, "Hello"};
    int id;
    std::string text;

    std::tie(id, text) = p;  // pair를 각각 id와 text로 분리
    std::cout << id << ", " << text << std::endl;  // 출력: 1, Hello
    return 0;
}

2. 주요 클래스 및 함수 요약

클래스/함수설명

std::pair 두 개의 값을 저장하는 템플릿 클래스
std::make_pair std::pair를 생성하는 함수
std::move 객체의 소유권을 이동시킴 (이동 시멘틱 구현)
std::swap 두 변수의 값을 교환
std::forward 함수 템플릿에서 인수의 값을 완벽히 전달
std::tie std::pair나 std::tuple의 값을 각각의 변수로 해체

 

'공부한거 > C++' 카테고리의 다른 글

#include <string>  (0) 2024.11.21
#include <exception>  (0) 2024.11.21
#include <array>  (0) 2024.11.21
느낌대로 namespace 정의  (0) 2024.11.21
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함