[c++][알고리즘] 내가 알고리즘 풀 때 참고할 팁들 정리 (수정)

이준규·2021년 12월 18일
0

알고리즘

목록 보기
3/7
  • sort 함수 문자열 정렬은

앞자리부터 차례로 비교함

  • map 정렬하기

벡터에 pair형으로 넣는다 그 후 벡터 정렬

map<string, int> m;

vector<pair<string, int>> com(m.begin(), m.end());

sort(com.begin(), com.end(), compare);
  • str.find 함수

not found → string::npos 반환

if (str.find("string") != std::string::npos) {
    	cout << "찾는 문자가 존재합니다";

    	int index = str.find("string");   
        //해당 문자의 시작 인덱스 반환
	}
    }
  • 벡터 중복제거

    • sort(begin, end)
    • erase(unique(begin, end), end)
  • lower_bound


인덱스를 찾고자하면 - begin을 한다

  • 메모리 초기화

memset(arr, value ,sizeof(arr))

  • 벡터 최소 최대값
vector<int> v;
cout << "max값: " << *max_element(v.begin(), v.end()) << endl;
cout << "min값: " << *min_element(v.begin(), v.end()) << endl;

string str = "algorithm";
cout << *min_element(str.begin(), str.end()) << endl;
cout << *max_element(str.begin(), str.end()) << endl;


int *arr = new int[size];
cout << "max값: " << *max_element(arr, arr+size) << endl;
cout << "min값: " << *min_element(arr, arr+size) << endl;
  • long long 쓸때

using ll = long long;


#include <queue>

    priority_queue<int> pq;  
    // - >  priority_queue<int, vector<int>, less<int>> pq;
}
priority_queue<int, vector<int>, greater<int>> pq1;
priority_queue<int, vector<int>, less<int>> pq2;

push()
pop()
empty()
top()
size()

push의 경우 단순히 queue에 값을 넣어준다. 다시 말하면 오브젝트로 제작후 삽입하므로 불필요한 복사가 많이 일어난다.

emplace의 경우 오브젝트를 생성하지 않고 바로 값을 넣는다. 즉, copy와 constructor가 합쳐진 것이라 볼 수 있다.

https://jungeu1509.github.io/algorithm/use-priorityqueue/ 출처


구조체 사용법

struct s{
  int i;
  int c;
  
  s(int num, int alpha) : i(num), c(alpha) {}
};

struct cmp {
  bool operator()(s a, s b) {
    return a.c > b.c;
  }
};


    priority_queue <s, vector<s>, cmp> pq;



    pq.push(s(jobs[size - 1][0], jobs[size - 1][1]));
    
    

include set 을 사용하면 더 편함

자동정렬됨


https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=lsm_origin&logNo=220079240439
ㅡmap 사용


PQ compare 만들기 우선순위큐

struct compare {
    bool operator()(pair<int, int> a, pair<int, int> b) {
        if (a.second == b.second) return a.first > b.first;
        else return a.second > b.second;
    }
};

int main()
{
    
    priority_queue<pair<int, int>, vector<pair<int, int>>, compare> pq;

vector index == i 일때 (iter 말고) 삭제하는법

v.erase(v.begin() + i);


map 사용법 정리

https://life-with-coding.tistory.com/305

#include 은 key 정렬된 컨테이너임.

최대공약수

int gcd (int a, int b) {
  if (b == 0) {
      return a;
  } else {
      return gcd(b, a % b);
  }
  
}

string to int == stoi();

int to string == to_string();


숫자인지 아닌지

#include
isdigit () 0이면 숫자아님

... 수정중

profile
백엔드

0개의 댓글