2019. 7. 25. 02:55ㆍComputerScience/C-C++
tuple<string, char, int> t = {"lee", 'Y', 12};
auto [name,check,age] = t; // string name = lee, char check = Y, int age = 12
pair<int,int> p = {1,2};
auto [x,y] = p; // int x= 1, int y =2
너무 편해버림
tuple이나 구조체로부터 여러 변수를 동시해 초기화
tuple<double,int,int> t = {1.2, 6, 30}
auto &[a,b,c] = t;
// double &a = 1.2, int &b=6, int &c = 30
a = 1.3
cout << get<0>(t);
// 실행결과 1.3
int arr[3] = {1,2,3};
auto &[x,y,z] = arr;
// int &x = arr[0], int &y = arr[1], int &z = arr[2]
x = 12;
cout << arr[0];
//실행결과 12
데이터 타입이 어떻게 매치되는지 유의하자.
map과 같은 자료구조에도 사용이 가능하다. pair나 map에서는 직관성이 올라간것같다.
struct S {
int x : 2;
int y;
};
int main()
{
S a;
a.x = 1;
a.y = 2;
auto[q, w] = a;
cout << q;
return 0;
}
구조체도 가능하다. 비정적이며 접근가능한 멤버변수만 대응되어 분리된다.
자세한내용은 다음을 참고하자.
https://en.cppreference.com/w/cpp/language/structured_binding
Structured binding declaration (since C++17) - cppreference.com
Binds the specified names to subobjects or elements of the initializer. Like a reference, a structured binding is an alias to an existing object. Unlike a reference, the type of a structured binding does not have to be a reference type. attr(optional) cv-a
en.cppreference.com
C++17에서는 reference 도 가능하다. Visual Studio에서 구문오류가 날 경우(컴파일러 오류 C2429)
프로젝트 - 프로젝트 설정 - C/C++ - 언어 - C++언어표준 에서 /std:c++17으로 설정하면 구문오류는 해결된다.
'ComputerScience > C-C++' 카테고리의 다른 글
[gcc/g++] long double operate error (0) | 2021.10.01 |
---|---|
vector 선언,초기화와 정적 배열 초기화 속도차이 (0) | 2019.09.30 |
자잘한 문법들 (0) | 2019.07.25 |
문자열(string)으로 입력받기, 문자열 쪼개기::string stream (0) | 2019.07.09 |
클래스 템플릿// 멤버함수의 외부 선언 (0) | 2019.05.12 |