pair
-
pair를 사용하면 두 자료형 T1과 T2를 묶을 수 있다
-
항상 두 개를 묶는다
-
첫 번째 자료는 first
-
두 번째 자료는 second로 접근할 수 있다.
-
#include <utility> 에 있는데, algorithm, vector와 같은 헤더파일에서 이미 include 하고 있기 때문에 따로 include 하는 경우는 없다.
-
make_pair를 이용하거나, 생성자를 이용해서 만들 수 있다.
pair_example01.cpp
pair<int, int> p1;
cout << p1.first << ' ' << p1.second << '\n';
p1 = make_pair(10, 20);
cout << p1.first << ' ' << p1.second << '\n'
p1 = pair<int, int>(30, 40);
cout << p1.first << ' ' << p1.second << '\n'
pair<int, int> p2(50, 60);
cout << p2.first << ' ' << p2.second << '\n';
pair_example02.cpp
pair<pair<int, int>> p = make_pair(make_pair(10, 20), make_pair(30, 40));
cout << p.first.first << ' ' << p.first.second << ' ';
cout << p.second.first << ' ' << p.second.second << '\n';
tuple
-
tuple은 pair와 같지만 여러 개를 묶을 수 있다
-
.first, .second, .third, .fourth … 가 아니고 get을 이용해서 인덱스로 접근해야 한다
-
tuple은 #include <tuple>에 정의되어 있다
tuple_example01.cpp
tuple<int, int, int> t1 = make_tuple(1, 2, 3);
cout << get<0>(t1) << ' ';
cout << get<1>(t1) << ' ';
cout << get<2>(t1) << '\n';
/*
for (int i=0; i<3; i++) {
count << get<i>(t1) << '\n';
}
*/
-
get<> 사이에 변수를 넣을 수는 없다
tie
tie_example01.cpp
auto t = make_tuple(10, 20, 30);
int x = get<0>(t);
int y = get<1>(t);
int z = get<2>(t);
cout << x << ' ' << y << ' ' << z << '\n';
x = y = z = 0;
tie(x, y, z) = t; // (10, 20, 30)
cout << x << ' ' << y << ' ' << z << '\n';
-
tie는 pair에도 사용할 수 있다.
-
변수값을 무시해야 하는 경우에는 ignore를 사용한다
tie_example02.cpp
auto t = make_tuple(1, 2, 3);
int x, y;
tie(x, y, ignore) = t; // (1, 2)
cout << x << ' ' << y << '\n';
vector
-
vector는 배열이다.
-
길이를 변경할 수 있는 배열이다
-
#include <vector>
vector_example01.cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v1; // 길이가 0
vector<int> v2(10); // 길이가 10
vector<int> v3(15, 1); // 길이가 15, 초기값 1
vector<int> v4 = {1, 2, 3, 4, 5};
return 0;
}
vector_example02.cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<pair<int, int>>v5;
vector<pair<int, int>>v6 = {{1, 2}, {3, 4}};
vector<vector<int>> v7;
int n = 10, m = 20,
vector<vector<int>> v8(n, vector<int>(m));
return 0;
}