#include <iostream>
#include <stack>
#include <string>
using namespace std;
//스택은 가장나중에 들어온게 가장 먼저 나간다.
int main()
{
int n,count=0;
string str;
string word;
stack<string> s;
cin>>n;
cin.ignore();
for(int i=0; i<n; i++)
{
count=0;
getline(cin,str);
//공백이나 끝에 도달하면 그 단어를 스택에 집어넣는다.
for(int j=0; j<=str.length(); j++)
{
if(str[j]==' '||j==str.length())
{
count++;
s.push(word);
word.clear();
}
else
{
//글자모으기
word=word+str[j];
}
}
cout<< "Case #"<<i+1<<": ";
//가장 나중에 들어간 것부터 출력한다.
for(int j=0; j<count; j++)
{
cout<<s.top()<<' ';
s.pop();
}
cout<<'\n';
}
}
3.깨달은점
문자열도 스택에 쓰여질수 있다는 것을 알았다. #include <stack>라이브러리를 사용한것은 이번이 처음인데 스택의 연산은 push가 삽입이고 pop이 스택의 top원소를 제거한다. top은 가장 나중에(늦게)들어온 자료를 나가게한다.
1.아이디어
처음에 pair벡터를 이용해 받고 sort를 이용해 정렬을 해야하는 것까지는 구현을 했다. 하지만 나이가 같으면 먼저 들어온 순으로 출력을 해야하는 것을 몰라서 구글링을했다. 처음에 sort를 사용하여 입출력이 맞게 나왔지만 틀렸습니다가 나왔다.
//pair 벡터를 이용해 하나씩받고 sort를 이용해 정렬을한다
//나이가 같으면 compare를 이용해 먼저들어온사람을출력.
#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>
using namespace std;
//나이순으로 정렬 나이만 정렬함.
bool compare(pair<int,string>x, pair<int,string>y)
{
return x.first<y.first;
}
int main()
{
int n;
vector <pair<int,string>> v;
cin>>n;
cin.ignore();
//n번만큼 회원의 나이와 이름을 받는다
for(int i=0; i<n; i++)
{
//first에 나이를 second에 이름을 받는다
int tmp;
string tmp2;
cin>>tmp>>tmp2;
v.push_back(pair<int,string>(tmp,tmp2));
}
stable_sort(v.begin(),v.end(),compare);
for(int j=0; j<n; j++)
{
cout<<v[j].first<<" "<<v[j].second;
if(j!=n-1)
{
cout<<'\n';
}
}
}
3.깨달은점
sort는 정렬 비교하는 두값이 같을때 두 elements의 위치를 보존한다고 장담할수 없는 반면,stable_sort는 위와 같은 상화에 두 elementes의 위치(순서)를 보존해준다. 다시한번 정리를 해보자면 stable_sort는 객체의 순서를 보존해준다!