코딩테스트 앗차 모음집

파닥몬·2022년 7월 1일
0
post-thumbnail

코딩테스트를 준비하며 자주 까먹어서 '앗차!'하는 부분을 정리해보고자 한다.
이름하야 앗차 모음집...!!!
(생길 때마다 조금씩 추가할 예정)

1) c++로 문자열 split

  • python에선 split 함수가 있어서 편하게 자를 수 있지만, c++은 어림없다.
  • 준비물 : vector<string>(자른 거 담을 그릇), string(자른 거)
#include <sstream>

vector<string> split;
string buffer;
// i-string-stream
istringstream ss(자를 문자열 대상);
// 순서 중요하긔
while(getline(ss, buffer, ' ')) {
	split.push_back(buffer);
}

2) tuple 이용

  • pair<int, pair<int,int>>가 귀찮을 때가 있다.
#include <tuple>

// tuple을 정의하는 3가지 방법
// tuple<int, int> t=make_tuple(1, 2);
// tuple<int, int> t(1, 2)
tuple<int, int> t= {1, 2};

// tuple 값 추출 => get<원하는 index>(tuple 이름)
int first = get<0>(t);

3) typedef 이용

  • long long 이런 거 계속 쓰기 힘들 때 치환하기 유용하다!
typedef long long ll;
또는
#define ll long long

4) string ↔️ int

// string -> int
int tmp = stoi(str);
// int -> string
string tmp = to_string(int);

5) vector에서 중복 제거

  • 굉장히 많이 쓰이는 코드다. map이나 set으로 중복제거를 할 수도 있다.
// erase(unique, v.end())
v.erase(unique(v.begin(), v.end()), v.end());

6) 소수 판별

#include <cmath>

int isPrime(int num){
	// 0과 1은 소수가 아니다. (예외 처리)
	if(num==0 || num==1) return 0;
    for(int i=2; i<=sqrt(num); i++){
    	// 나눠진다는 건, 약수가 있다는 뜻이니 소수가 될 수 없다.
    	if(num%i==0) return 0;
    }
    return 1;
}

7) type 변환

  • 후... 이거 때문에 코테에서 울뻔했다. 늘 잊지말자규~!!!
  • string에서 char로 바꾸는 방법을 몰랐는데, 찾아보니까 str[index]이 char였다. ㅎ... 보고 아 맞다!!! 이런 생각. 왜 생각이 안 났을까...😢
// int to string ➡️ int 외에 float, double도 가능.
to_string(i);
// string to int ➡️ stof(float), stod(double), stoll(long long)
stoi(str);

// char* to string ➡️ c_str()로 char로 바꾸고, 
char ch1[5]={'a','b','c','d','e'};
char* ch2="abcde";
strcpy(ch1, str.c_str());
// string to char* ➡️ string 선언할 때, char 변수를 괄호에 넣는다.
string str(ch)1;

#include <cstdlib>
// int to char (0이상 10 미만 int만 가능)
char c='9';
int i=c-'0';
// char* to int
char ch[3]="120"
atoi(ch)

8) 구조체 생성자

struct S{
    int x, y, z;
    S(int X, int Y, int Z) : x(X), y(Y), z(Z) {}
};

S(10, 20, 30);
S* tmp=new S(10, 20, 30);

9) ceil, floor

  • 자주 헷갈리는 이름...!
  • 만약 a/b 의 값을 올림(or 내림) 하고 싶다면, a나 b 중 하나는 float여야 한다.
// 천장이니까 TOP => 올림
ceil() 
// 바닥이니까 BOTTOM => 내림
floor()

10) 아스키코드

  1. 영어 대문자 : 65~90
  2. 영어 소문자 : 97~122
  3. 숫자 : 48~57

VERSION 정보
ver1. 1,2,3,4,5번 작성 (~2022.07.01)
ver2. 6,7,8번 작성 (~2022.07.03)
ver3. 9,10번 작성(~2022.09.07)

profile
파닥파닥

2개의 댓글

comment-user-thumbnail
2022년 7월 2일

좋은 팁 감사합니다 ☺️

1개의 답글