본문 바로가기

C++/C++ 문법

C++ Structured Binding(구조적 바인딩)

728x90
728x90

C++17부터 지원하는 structured binding이란 어떤 배열, STL 같은 컨테이너에서 멤버들을 쉽게 바인딩할 수 있도록 도와주는 문법이다.

 

친숙한 std::map을 예시로 바인딩을 해보자.

 

#include <iostream>
#include <map>

int main()
{
  std::map<int, int> mp;

  for (int i = 1; i < 11; i++)
  {
    mp[i] = i * i;
  }

  // iterator, basic for
  for (std::map<int, int>::iterator it = mp.begin(); it != mp.end(); it++)
  {
    std::cout << it->first << ' ' << it->second << '\n';
  }

  // auto, enhanced for
  for (auto &i: mp)
  {
    std::cout << i.first << ' ' << i.second << '\n';
  }

  // structured binding, enhanced for
  for (auto &[k, v]: mp)
  {
    std::cout << k << ' ' << v << '\n';
  }
}

 

세 for 문은 같은 출력을 보여준다. 마지막에 있는 for 문이 structured binding을 사용하여 map에 key와 value를 꺼내온 것이다.

 

이렇게 꺼내올 멤버들의 이름을 지정하고 대괄호로 묶어주면 각 멤버가 알맞는 순서의 값을 매핑해온다.

 

std::array의 모든 원소를 가져와보자.

 

#include <iostream>
#include <array>

int main()
{
  std::array<int, 5> ar;
  for (int i = 0; i < 5; ++i) ar[i] = i + 1;
  auto [a, b, c, d, e] = ar;
  std::cout << a << ' ' << b << ' ' << c << ' ' << d << ' ' << e << '\n';
}

 

해당 코드를 실행해보면 각 index의 원소가 순서대로 a, b, c, d, e에 대입하는 것을 볼 수 있다.

 

Structured binding은 서로 다른 타입이 들어있는 std::tuple에도 사용이 가능하다.

 

#include <iostream>
#include <string>
#include <tuple>

int main()
{
  std::tuple<int, std::string, std::string> tp;

  std::get<0>(tp) = 10;
  std::get<1>(tp) = "HELLO";
  std::get<2>(tp) = "WORLD!";

  auto [a, b, c] = tp;

  std::cout << a << ' ' << b << ' ' << c << '\n';
}

 

이렇게 STL에서 쓰는 것 뿐만 아니라 직접 정의한 구조체에도 사용이 가능하다.

 

#include <iostream>

struct point2d
{
  int x, y;
};

int main()
{
  point2d p;
  p.x = 10, p.y = 2000;

  auto &[a, b] = p;

  a = 200, b = 0;

  std::cout << p.x << ' ' << p.y << '\n';
}

 

바인딩한 멤버에 레퍼런스를 걸어 본래 구조체의 멤버 값을 바꾸는 것을 볼 수 있다.

 

이렇게 structured binding은 상당히 편리하게 멤버를 이용할 수 있게 해 주니 C++17 이상의 환경을 사용한다면 사용하는 것이 좋다.

728x90
728x90

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

C++ if statement with initializer  (0) 2021.11.14
C++ 람다 표현식 lambda expression  (0) 2021.09.03