tuple<> 을 처음 알게되어 기록해본다.
[파일명 정렬] 이라는 문제를 풀다가 원소3개를 한 번에 저장하고 싶어서 찾아봤었다.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<string> solution(vector<string> files) {
vector<string> answer;
vector<tuple<string, int, int>> record; //[[HEAD, NUMBER, Index], ...]
for(int i=0; i<files.size(); i++)
{
string head = "";
string number = "";
string tail = "";
for(auto f: files[i])
{
if(tail.empty() && (f >= 48 && f <= 57))
{
number += f;
}
else if(number.empty())
{
head += tolower(f);
}
else
{
tail += f;
}
}
// record에 HEAD, NUMBER 저장
record.push_back({head, stoi(number), i});
}
sort(record.begin(), record.end(), [](auto& lh, auto& rh){
string lhead = get<0>(lh), rhead = get<0>(rh);
int lnum = get<1>(lh), rnum = get<1>(rh);
int lidx = get<2>(lh), ridx = get<2>(rh);
if(lhead == rhead)
{
if(lnum == rnum)
{
return lidx < ridx;
}
return lnum < rnum;
}
return lhead < rhead;
});
for(auto& [head, number, idx] : record)
{
answer.push_back(files[idx]);
}
return answer;
}
vector<tuple<string, int, int>> record;는 C++에서 튜플을 원소로 가지는 벡터를 의미한다. 이 구조는 여러 개의 서로 다른 타입의 값을 하나의 묶음으로 저장할 때 유용하다.
tuple<string, int, int>이란?tuple은 여러 개의 서로 다른 타입의 데이터를 하나로 묶은 자료형이다.
tuple<string, int, int> example = make_tuple("Alice", 90, 100);
이 경우:
| 튜플 요소 | 값 | 타입 |
|---|---|---|
| 첫 번째 | "Alice" | string |
| 두 번째 | 90 | int |
| 세 번째 | 100 | int |
tuple<string, int, int> t = make_tuple("Tom", 85, 92);
vector<tuple<string, int, int>> record;
record.push_back(make_tuple("Tom", 85, 92));
record.push_back(make_tuple("Jane", 78, 88));
for (auto& r : record) {
string name;
int score1, score2;
tie(name, score1, score2) = r;
cout << name << " " << score1 << " " << score2 << endl;
}
또는:
cout << get<0>(r) << " " << get<1>(r) << " " << get<2>(r) << endl;
get<0>(r)→ 튜플의 첫 번째 요소,get<1>(r)→ 두 번째 요소, ...
struct를 따로 만들지 않고도 여러 타입의 값을 한 묶음으로 처리할 수 있어서