코딩테스트
C++ 코테 준비에서 알면 좋은 프로그래밍 기법.
codingfeature
2023. 12. 25. 15:06
개인적으로 코딩테스트에서 사용하기 위해 기억하면 좋을 프로그래밍 기법들을 정리해보았습니다.
생각날 때마다 계속해서 업데이트 할 예정입니다!
공백을 포함한 문자열 입력 받기(getline)
int main() {
string str;
getline(cin, s);
cout << str;
}
문자열 파싱
sstream 라이브러리 이용.
아래는 "12 23 34 45", 공백으로 각 Interger가 나뉘어져 있는 문자열을 파싱하고 sum을 구하는 코드입니다.
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string str = "12 23 34 45";
stringstream ss(str);
int A, sum = 0;
while(ss >> A){
sum += A;
cout << A << ' ' << sum << '\n';
}
return 0;
}
/*
결과:
12 12
23 35
34 69
45 114
*/
문자열 연결(합치기)
1. '+' 사용
string 형은 파이썬같이 +를 이용해서 합칠 수 있습니다.
#include <iostream>
using namespace std;
int main() {
string str1 = "Hello ";
string str2 = "World! ";
string str3;
str3 = str1 + str2;
cout << str3;
return 0;
}
/*
결과:
Hello World!
*/
문자열 내 자르기
substr 사용.
string str1 = "0123456789";
string str2 = str1.substr(4, 3);
// substr(시작 index, 문자열 길이)
cout << str2; // 결과값 : 456
String과 Integer 변환
String -> Integer
1. stoi 사용
stoi는 string과 char 배열에 담긴 숫자를 interger 형태로 변환해줍니다.
아래는 string으로 저장된 "12"와 char 배열로 저장된 "23"을 각각 stoi를 사용해 integer로 변환시켜주고 더해주는 코드입니다.
#include <iostream>
using namespace std;
int main() {
string str = "12";
char char_str[3] = "23";
int A = stoi(str) + stoi(char_str);
cout << A;
return 0;
}
/*
결과:
35
*/
2. sstream 라이브러리 사용.
stoi 함수보다는 덜 직관적이지만 sstream을 사용해서 string을 int로 변환할 수 있습니다.
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string str = "12";
char char_str[3] = "23";
int temp, sum = 0;
stringstream ss1(str), ss2(char_str);
ss1 >> temp;
sum += temp;
ss2 >> temp;
sum += temp;
cout << sum;
return 0;
}
Integer -> String
to_string 함수 사용.
#include <iostream>
using namespace std;
int main() {
string str;
str = to_string(123) + " " + to_string(456);
cout << str;
return 0;
}
/*
결과:
123 456
*/
Vector 내 원소 순회하기
1. size 함수 사용.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
int vec_size = vec.size();
for(int i=0;i<vec_size;i++){
cout << vec[i] << ' '; // 출력: 1 2 3 4 5
}
return 0;
}
2. auto 키워드 사용.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
for(auto & element : vec){
cout << element << ' '; // 출력 : 1 2 3 4 5
}
return 0;
}