C++:: 코딩테스트에서 자주사용하는 내장함수 간단정리

jahlee·2023년 3월 9일
0

개인 공부

목록 보기
1/23
post-thumbnail

모든 함수들에 대해 간단한 사용방법 정도만 정리를 해두었기 떄문에 자세한 함수 설명은 따로 검색해서 공부하면 된다.

#include <bits/stdc++.h>를 사용하면 모든헤더를 하나도 묶어서 불러올 수 도 있다. 하지만 공부할때는 직접 해당 함수의 헤더를 쓰면서 어느 헤더의 함수인지 공부하는게 좋다.

#include < bitset >

정수를 이진수로 변환 시켜줄때 사용할 수 있는 헤더이다.

1. bitset< int n >(int m)

int main()
{
	// bitset<이진수로 변환했을때 자리수> (변환하고싶은 10진수)
    bitset<10> test(8);
    cout << test << "\n";
    // bitset<>().to_string() 을 통해 string으로 반환도 가능하다. 
    string binary = bitset<4>(8).to_string();
    cout << binary << "\n";
}

#include < algorithm >

1. sort(시작,끝,정렬방법)

기본적으로 사전순 오름차순으로 정렬이 되지만 따로 정렬방법인 compare함수를 구현하여
매개변수로 넣어준다면 원하는 정렬방법으로도 정렬이 가능하다.

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;

bool compare(pair<int,string> a, pair<int,string> b)// 내림차순 예시
{
	if (a.first == b.first) return (a.second > b.second);
    return (a.first > b.first);
}

int main()
{
	vector<pair<int,string>> v;
    string s[4] = {"sort", "compare", "function", "test"};
    for(int i=0;i<4;i++) v.push_back({s[i].size(), s[i]});
    sort(v.begin(), v.end());// 단순 오름차순 정렬
    cout << "단순오름차순\n";
    for(auto c : v) cout << c.first << " " << c.second << "\n";
    sort(v.begin(), v.end(), compare);
    cout << "compare함수 구현 정렬\n";
    for(auto c : v) cout << c.first << " " << c.second << "\n";
}
/* 실행 결과
    단순오름차순
    4 sort
    4 test
    7 compare
    8 function
    compare함수 구현 정렬
    8 function
    7 compare
    4 test
    4 sort
*/

2. unique(시작, 끝)

시작 지점부터 끝지점까지 중복원소를 뒤로 밀어주고 중복원소의 지점을 반환해준다.
주의할 점은 정렬이 되어진 컨테이너에서만 제대로 동작한다는 점이다.
주로 단독으로는 사용하지 않고 erase함수와 같이 사용한다.
v.erase(unique(v.begin(), v.end()), v.end());

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
	vector<int> v1 = {1,1,2,3,4,5,5};
	vector<int> v2 = {1,1,1,2,3,3,4,5};
    cout << "< 예시 1 >\n";
    cout << "unique 사용전\n";
    for(auto c : v1) cout << c << " ";
    unique(v1.begin(), v1.end());
    cout << "\nunique 후\n";
    for(auto c : v1) cout << c << " ";

    cout << "\n< 예시 2 >\n";
    cout << "unique 사용전\n";
    for(auto c : v2) cout << c << " ";
    unique(v2.begin(), v2.begin() + 5);// 전체범위에 대해 하는 경우가 아닐때는 조심하여 사용하여야 한다.
    cout << "\nunique 후\n";
    for(auto c : v2) cout << c << " ";

}
/* 실행 결과
    < 예시 1 >
    unique 사용전
    1 1 2 3 4 5 5
    unique 후
    1 2 3 4 5 5 5
    < 예시 2 >
    unique 사용전
    1 1 1 2 3 3 4 5
    unique 후
    1 2 3 2 3 3 4 5
*/

3. max(const T& a, const T& b) && min(const T& a, const T& b)

max 는 비교하여 큰 값 리턴
min 은 비교하여 작은 값 리턴

4. max_element(iterator.begin(), iterator.end()) && min_element(iterator.begin(), iterator.end())

해당 범위 내의 가장 큰값, 작은값을 가지는 iterator를 리턴해준다.
값을 사용할때는 *iter로 사용하면 된다.

5. next_permutation(iterator.begin(), iterator.end())

해당 벡터 내 인자들로 만들 수 있는 모든 가지수를 만들어준다. 주의해야할점은 사전순으로 정렬된 상태에서 넣어주어야 모든 가지수가 나오게된다는 점이다. 사전순 정렬이 안되어있다면 해당 정렬상태 부터의 가지수를 만들어준다.

#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

int main() {
    vector <char> v1 = { 'A','B','C' }; 
    vector <char> v2 = { 'B','C','A' };
    do {
        for (auto x : v1)cout << x; 
        cout << "\n"; 
    } while (next_permutation(v1.begin(), v1.end()));//계속해서 정렬
    cout << "\n"; 

    do {
        for (auto x : v2)cout << x;
        cout << "\n";
    } while (next_permutation(v2.begin(), v2.end()));//계속해서 정렬
    cout << "\n";
}

#include < string >

1. isdigit(char c);

문자가 숫자 0~9 이면 참을 리턴해준다.

2. string.substr(int idx, int len);

문자열 str의 idx인덱스 부터 len 만큼 뽑아서 새로운 문자열로 리턴해준다.

3. stoi(string s);

문자열을 정수형으로 변환 해준다.
이때 문자열 s가 온전히 숫자들로 이루어져 있다면 문제가 없지만
숫자 외 다른 문자가 존재한다면 그전까지의 숫자들만 변환하여 리턴한다.
<예시>
stoi("1234") => 1234
stoi("12:34") => 12

문자열의 시작은 무조건 숫자여야한다.

4. to_string(int num);

정수형을 문자열로 변환 해준다.

5. string.c_str();

스트링을 const char*로 바꾸어 리턴해준다.

5. string.compare(string comp);

두 스트링을 비교해서 다르다면 그 차이값을 반환해 주는 함수이다.
다음과 같이 시작 인덱스와 비교할 크기를 설정해 줄 수도 있다.

string.compare(int start_idx, int size, string comp);

#include < string.h >

1. void memset(void ptr, int value, size_t num);

메모리를 원하는 값으로 초기화 해주는 함수이다.
사용시 주의할점은 초기화를 할때 unsignd char 범위 내의 값으로 초기화 해주기 때문에
만약 예시로 인트 배열을 초기화 할때 0 또는 -1 로 초기화 하지않는 이상 함수가 제대로 동작하지 않을 수 있다.

2. void fill (ForwardIterator first, ForwardIterator last, const T& val);

시작위치 iter 부터 끝위치 iter까지 원하는 val로 채워주는 함수이다.

#include < vector >

1. vector 선언하고 바로 초기화

1. vector<int> v(size, 초기화 숫자);
2. 이중 벡터를 선언 초기화 하고 싶은 경우
	vector<vector<int> > v(size, vector<int>(size, 초기화 숫자));
3. for(int i=0;i<size;i++) v.push_back(-1);

비어있는 백터를 초기화 해줄때는 fill을 사용할 수 없다.

#include < iterator >

1. iter_swap(ForwardIt1 a, ForwardIt2 b);

두 iterator가 가리키는 데이터의 위치를 바꾸어준다.

#include <vector>
#include <iostream>
#include <iterator>
using namespace std;

int main()
{
	vector<int> v = {0,1,2,3,4,5};
	vector<int>::iterator iter = v.begin();
	iter_swap(iter+2, iter+3);
	for(auto c : v) cout << c << " ";
	cout << "\n";
}

/*
	➜  c++ -std=c++17 test.cpp 
	➜  ./a.out 
	0 1 3 2 4 5 
*/

#include < sstream >

1. stringstream ss(string str);

입출력이 가능한 스트림으로 바꾸어주는 기능을 한다. 이를 통해 간단하게 공백 혹은 개행을 기준으로 문자열을 나눠 줄 수 있다.

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
    // 방법 1
    string input = "abc def ghi 123";
    stringstream ss(input);
    vector<string> words;
    string word;
    while (getline(ss, word, ' ')){
        words.push_back(word);
    }
      
    // 방법 2
   	stringstream ss(input);
    vector<string> words(3);
    int num = 0;
    ss >> words[0] >> words[1] >> words[2] >> num;
}

2. istringstream ss(string str);

기본적으로 stringstream과 비슷한 기능을 가지고 있지만 입력만 가능한 스트림이라는 점이 다르다.

0개의 댓글