[코딩테스트] c++ 코딩테스트 준비 단계
💼 코딩테스트 준비 단계
취업 준비 혹은 이직 준비를 할 때 코딩테스트를 준비 하고 있는 경우가 많이 있을겁니다. 저도 코테 준비를 하고 있는 도중 유명한 회사에 들어 간 지인 분이 많은 팁을 알려줬습니다. 그래서 그 팁을 공유하고자 합니다. 물론 사람 생각마다 다를수도 있습니다. 😂
💻 Tip▪ 간결함, 정확함이 생명이다.
▪ C++ 혹은 파이썬으로 코딩 테스트 준비 하는게 좋다.
▪ C++ 경우 STL 라이브러리를 잘 알고 있어야 자료구조 직접 구현하는 헛짓을 안한다.
▪ 백준, 프로그래머스 홈페이지를 적극 사용
▪ 카카오톡 오픈 채팅 방으로 막히는 알고리즘 문제 질문하기
저는 코딩테스트를 코틀린(kotlin)으로 하다가 C++로 변경 했습니다.
C++ 팁도 몇가지 알려드릴려고 합니다.
C++ 문자열 처리
C++에서 문자열 처리는 번거롭습니다. 따라서 몇가지 팁을 알려드리겠습니다.
1️⃣ getline은 앞 뒤 개행문자들도 다 읽어옴.
▪ C++에서 stringstream은 주어진 문자열에서 필요한 자료형에 맞는 정보를 꺼낼 때 유용하게 사용됩니다.
🔎 일반 출력문 경우
#include<iostream>
#include<sstream>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
stringstream ss;
string str = "abc";
char buff;
ss.str(str);
while (ss >> buff)
cout << buff << endl;
// stream.str("");//초기화
return 0;
}
결과 :
a
b
c
🔎 cin으로 띄어 쓰기 문자열을 받은 경우
#include<iostream>
#include<sstream>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
stringstream ss;
string str;
cin >> str;
char buff;
ss.str(str);
while (ss >> buff)
cout << buff << endl;
return 0;
}
입력 : a b c
결과 :
a
🔎 getLine()으로 띄어 쓰기 문자열을 받은 경우
#include<iostream>
#include<sstream>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
stringstream ss;
string str;
char buff;
getline(cin, str);
ss.str(str);
while (ss >> buff)
cout << buff << endl;
return 0;
}
입력 : a b c
결과 :
a
b
c
🔎 getLine 주의 사항
cin 입력 후 getLine을 사용하면 입력 후 엔터값이 getLine에 들어가기 때문에 재대로 동작하지 않습니다.
#include<iostream>
#include<sstream>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
stringstream ss;
string str;
char buff;
int N;
cin >> N;
getline(cin, str);
ss.str(str);
cout << N << endl;
cout << str;
return 0;
}
입력 : 5
결과 : 5
따라서 cin.ignore()를 사용하여 버퍼를 비워줘야 합니다.
#include<iostream>
#include<sstream>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
stringstream ss;
string str;
char buff;
int N;
cin >> N;
cin.ignore();
getline(cin, str);
ss.str(str);
cout << N << endl;
cout << str;
return 0;
}
입력 :
5
5678
결과 :
5
5678
2️⃣ 숫자형 문자 (“0” ~ “9”)를 int로 바꾸고 싶을 땐 ‘0’을 빼기
char c = '1';
int n = c - '0';
// n = 1
3️⃣ str.find()를 못찾는 경우 string::npos를 반환하지만 -1을 반환한다고 생각해도 됨
string lines = "abcde, fh,";
lines.find(','); //찾지못한경우 npos반환 (-1), a시작해서 찾음
4️⃣ str.find(, index)로 하면 index부터 탐색
string lines = "abcde,";
lines.find(',', 2); //찾지못한경우 npos반환 (-1), c시작해서 찾음
5️⃣ str.erase(index, size) 삭제시작할 index, 그리고 크기
6️⃣ 문자열 자르기
🔎 string 클래스 사용 시
#include <string>
using namespace std;
int main() {
string lines = "hello,my,name,is";
size_t previous = 0, current;
current = lines.find(','); //찾지못한경우 npos반환
while(current !=string::npos) {
string substring = lines.substr(previous, current - previous);
cout << substring << " ";
previous = current + 1;
current = lines.find(',', previous);
}
cout << lines.substr(previous, current - previous);
return 0;
}
🔎 sstream 클래스 이용할때
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string lines = "hello my name is";
stringstream ss(lines);
string tmp;
vector <string> log;
while ((ss >> tmp)) {
log.push_back(tmp);
cout << tmp << "\n";
}
return 0;
}
🔎 대소문자 변환
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string word = "HELLO";
transform(word.begin(), word.end(), word.begin(), ::tolower);
cout << word << "\n"; // hello
// for (int i = 0; i < word.size(); i++)
// {
// word[i] = ::toupper(word[i]);
// }
transform(word.begin(), word.end(), word.begin(), ::toupper);
cout << word << "\n"; // HELLO
return 0;
}
🔎 특정 문자열 찾기
using namespace std;
string line = "hello my namloe is siyeon";
string word = "lo";
int pos = line.find(word);
while(pos != string::npos) { //찾지못할때까지 반복
cout<<line.substr(pos, word.size()) << "\n";
pos = line.find(word, pos+word.size());
}
🔎 알파벳 제외 특수문자 공백으로 바꾸기
#include <algorithm>
using namespace std;
bool wordChange(char c) {
return c == '\'' || !isalpha(c);
//파라미터 속 문자가 ' 이거나 alphabet이 아닌경우 return
}
int main() {
string line = "h{el@@lo \tmy \"namelo<<e is siy{eo>>>n";
replace_if(line.begin(), line.end(), wordChange, ' ');
cout << line << "\n";
return 0;
}
7️⃣ vector 초기화 및 삭제
🔎 초기화
vector<int> v(n); //0으로 n개 생성
vector<int> v(n, x); //x로 n개 원소 생성
v.resize(n) //기본값 0으로 백터 사이즈 더 키울수있음
🔎 삭제
v.erase(v.begin() + index) //이거로 index위치에 있는 데이터 삭제 가능
v.erase(v.begin() + s, v.begin() + e) //s 부터 e-1까지의 인덱스 삭제
8️⃣ 변수형 변환
🔎 str -> char
char cst[100];
string str = "hello";
strlen(cstr, str.c_str());
🔎 char → str✨
char cst[100];
char *cst = "hello";
string str = cst;
🔎 char → int✨
//int의 경우 '0'빼기
🔎 str → int✨
string str = "100";
int num;
num = atoi(str.c_str());
🔎 int → str
int num = 10;
string str;
str = to_string(num);
댓글남기기