숏컷 코드
cpp
#include <map>
#include <tuple>
std::pair<std::string, int> entry{"apple", 3};
auto [name, count] = entry; // .first/.second 대신 의미 있는 이름
std::map<std::string, int> scores{{"Kim", 90}, {"Lee", 85}};
for (const auto& [key, value] : scores) {
std::cout << key << ": " << value << "\n";
}문법
structured bindings — .first/.second를 이름으로 대체
pair.first, pair.second는 읽는 사람이 의미를 추론해야 합니다. structured bindings는 분해 시 의미 있는 이름을 붙여 가독성을 높입니다. C++17부터 사용 가능합니다.
cpp
// ❌ .first/.second — 의미가 불분명
auto result = std::make_pair(true, 42);
if (result.first) std::cout << result.second;
// ✅ structured bindings — 의도가 드러남
auto [success, value] = std::make_pair(true, 42);
if (success) std::cout << value;
// try_emplace 반환값 분해
auto [it, inserted] = scores.try_emplace("Park", 95);
if (inserted) std::cout << "새로 삽입: " << it->second;auto vs auto& vs const auto& — 복사 vs 참조
auto로 분해하면 복사가 발생합니다. 원본 수정이 필요하면 auto&, 수정 없이 읽기만 할 때는 const auto&를 사용합니다. 특히 map 순회에서 const auto&는 복사 비용을 없애 성능 차이가 납니다.
cpp
std::map<std::string, int> m{{"a", 1}, {"b", 2}};
// auto — 복사: key와 value가 새 변수에 복사됨
for (auto [key, value] : m) { ... }
// auto& — 참조: 원본 수정 가능
for (auto& [key, value] : m) {
value *= 2; // map의 value를 직접 수정
}
// const auto& — 읽기 전용 참조: 가장 효율적
for (const auto& [key, value] : m) {
std::cout << key << ": " << value; // 복사 없이 읽기
}분해 가능한 타입 — pair, tuple, 배열, 집합체
cpp
// std::tuple
auto [x, y, z] = std::make_tuple(1, 2.0, "three");
// 배열
int arr[] = {10, 20, 30};
auto [a, b, c] = arr;
// 단순 구조체 (집합체 — user-declared ctor 없는)
struct Point { int x, y; };
Point p{3, 4};
auto [px, py] = p;
// 바인딩 개수가 멤버 개수와 일치해야 함
// auto [only] = p; // ❌ 컴파일 오류 — 2개 멤버인데 1개 바인딩체크포인트
| 상황 | 적합한 선택 |
|---|---|
| 읽기만, 복사 없이 | const auto& [a, b] = x |
| 원본 값 수정 필요 | auto& [a, b] = x |
| 독립 복사본 필요 | auto [a, b] = x |
| map 순회 (읽기) | for (const auto& [k, v] : m) |
| map 순회 (값 수정) | for (auto& [k, v] : m) |
| 삽입 결과 분해 | auto [it, inserted] = m.try_emplace(...) |
주의할 점
auto로 분해하면 복사가 발생합니다. 큰 맵이나 문자열을 순회할 때 const auto& 없이 쓰면 성능이 크게 떨어질 수 있습니다.
cpp
std::map<std::string, std::vector<int>> bigMap;
// ❌ auto — string key와 vector value가 매 반복마다 복사됨
for (auto [key, value] : bigMap) { ... }
// ✅ const auto& — 복사 없이 참조
for (const auto& [key, value] : bigMap) { ... }
// ⚠️ structured bindings는 집합체(aggregate)에만 적용
// user-declared 생성자가 있는 클래스는 직접 지원 안 됨
class Foo { Foo(int x, int y); int x_, y_; };
// auto [a, b] = Foo{1, 2}; // ❌ 컴파일 오류참고 링크
1 sources