※ 이번 문제에서 알게된 점
if (!s.compare("문자열"))
§ a.compare(b) 함수
C++에서 string 헤더에 제공되는 함수.
a와 b의 문자열이 서로 같다면 return 0
a와 b의 문자열이 서로 다르면 return -1
§ if (!s.compare("문자열"))
문자열이 같으면 0을 반환하므로 if(0)은 if (false)와 동일하게 취급된다.
따라서 if (!s.compare("문자열")은 if (!0) 즉, if (!false) == if(true)이다.
§ my solution
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main(){
int n; cin >> n;
stack<int> intStack;
for (int i = 0; i < n; i++) {
string s; cin >> s;
if (!s.compare("push")){
int push_num; cin >> push_num;
intStack.push(push_num);
}
else if (!s.compare("pop")){
if (intStack.empty())
cout << "-1" << endl;
else{
cout << intStack.top() << endl;
intStack.pop();
}
}
else if (!s.compare("size")){
cout << intStack.size() << endl;
}
else if (!s.compare("empty")){
if (intStack.empty())
cout << "1" << endl;
else
cout << "0" << endl;
}
else if (!s.compare("top")){
if (intStack.empty())
cout << "-1" << endl;
else
cout << intStack.top() << endl;
}
}
}
'Algorithms > Coding Test' 카테고리의 다른 글
[Baekjoon/백준] 10867번: 중복 빼고 정렬하기(C/C++) (0) | 2022.11.03 |
---|---|
[Baekjoon/백준] 11728번: 배열 합치기_merge(C/C++) / (알게된 점 多) (0) | 2022.11.03 |
[Baekjoon/백준] 2161번: 카드1_deque(C/C++) / (알게된 점X) (0) | 2022.11.02 |
[Baekjoon/백준] 2164번: 카드2_deque(C/C++) / (알게된 점X) (0) | 2022.11.02 |
[Baekjoon/백준] 1158번: 요세푸스 문제 0_deque(C/C++) (0) | 2022.11.01 |