티스토리 뷰
728x90
자료구조 List로 구현하면 되겠다라고 생각했다. 그리고 쉬운 문제라고 생각했는데 꽤 오래 걸렸다. 자괴감 ON
처음에는 아예 문자열 자체를 벡터에 넣어보기도 하고 string으로 하나하나 따라서 구현하다가 이상함을 느꼈고 시간은 1시간이 흘러있었다. 다시 노트에 끄적여보니 커서가 생각났다. 이거 그냥 편집기와 동일한 것 같다!란 생각
그래서 커서를 구현하려니까 이터레이터가 생각났다.
문제는 처음에 리스트에 아무것도 없어서 지정해봤자. 이터레이터가 가리키는 곳이 없다.?
그래서 커서를 따로 내가 int형으로 구현해서 index로 가리켜주자.란 생각으로 구현했다.
#include "iostream"
#include <vector>
using namespace std;
int main(){
int T;
cin >> T;
while(T--){
vector<char> v;
int cusor = 0;
string s;
cin >> s;
for(int i=0; i<s.length(); i++){
if(s[i] == '<'){
if(v.size() != 0) cusor--;
} else if(s[i] == '>'){
if(cusor < v.size() ) cusor++;
} else if(s[i] == '-'){
if(cusor != 0){
auto it = v.begin();
v.erase(it+cusor-1);
}
} else{
v.insert(v.begin()+cusor,s[i]);
cusor++;
}
}
for(auto it = v.begin(); it!=v.end(); it++)
cout << *it;
cout << "\n";
}
음! 안된다! 런타임 에러가 뜬다.뭐가 문제인지 모르겠다.
그래서 수정했다.
#include "iostream"
#include <list>
using namespace std;
int main(){
int T;
cin >> T;
while(T--){
list<char> v;
int cursor = 0;
string s;
cin >> s;
for(int i=0; i<s.length(); i++){
if(s[i] == '<'){
if(v.size() != 0) cursor--;
} else if(s[i] == '>'){
if(cursor < v.size() ) cursor++;
} else if(s[i] == '-'){
if(v.size() != 0){
auto it = v.begin();
for(int i=0; i<cursor-1; i++) it++;
v.erase(it);
}
} else{
auto it = v.begin();
for(int i=0; i<cursor; i++) it++;
v.insert(it,s[i]);
cursor++;
}
}
for(auto it = v.begin(); it!=v.end(); it++)
cout << *it;
cout << "\n";
}
}
또 런타임 에러가 난다! 코드가 더럽다. 복잡하고 억지스럽다.
#include "iostream"
#include <list>
using namespace std;
int main(){
ios::sync_with_stdio(NULL);
cin.tie(0);
int T;
cin >> T;
while(T--){
list<char> v;
auto cursor = v.begin();
string s;
cin >> s;
for(int i=0; i<s.length(); i++){
if(s[i] == '<'){
if(v.begin() != cursor) cursor--;
} else if(s[i] == '>'){
if(cursor != v.end() ) cursor++;
} else if(s[i] == '-'){
if(cursor != v.begin()){
cursor--;
cursor = v.erase(cursor);
}
} else{
cursor = v.insert(cursor,s[i]);
cursor++;
}
}
for(auto it = v.begin(); it!=v.end(); it++)
cout << *it;
cout << "\n";
}
}
이터레이터를 사용하는 방법을 알게되었다. 지정 안 되었던 이터레이터를 삽입할 때 지정해주고, 제거할 때 도 지정해준다. 이런 식으로 코드가 훨씬 깔끔하다.
숙제가 남았다. int cursor로 어떻게 구현해서 백준 문제를 통과할 수 있을까?
반응형
'코딩 관련 > c++' 카테고리의 다른 글
백준 5430 AC C++ 눈물 나와 (0) | 2020.05.09 |
---|---|
백준 1021 회전하는 큐 c++ (0) | 2020.05.09 |
백준 1003번 피보나치 함수 C++ (0) | 2020.05.06 |
백준 1620 나는야 포켓몬 마스터 이다솜 (0) | 2020.05.03 |
백준 1966 프로그래머스 Level 2 프린터 큐 Java c++ (0) | 2020.04.24 |