KimMinJun
Coding Note
KimMinJun
전체 방문자
오늘
어제
  • 분류 전체보기 (486)
    • ALGORITHM (11)
      • 정렬 (6)
      • 최단경로 (1)
      • 자료구조 (1)
      • 슬라이딩 윈도우 (1)
      • etc (2)
    • Git (5)
    • Web (24)
      • Vanilla JS (13)
      • TS (2)
      • React (7)
      • ETC (1)
    • React 공식문서 (번역, 공부) (11)
      • Quick Start (2)
      • Installation (0)
      • Describing the UI (9)
      • Adding Interactivity (0)
      • Managing State (0)
      • Escape Hatches (0)
    • Next.js 공식문서 (번역, 공부) (3)
      • Getting Started (2)
      • Building Your Application (1)
    • PS (431)
      • 백준 (187)
      • Programmers (104)
      • CodeUp (21)
      • STL (3)
      • 제코베 JS 100제 (50)
      • SWEA (0)
      • LeetCode (65)
    • IT (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 관리

공지사항

인기 글

태그

  • Level 1
  • Level 0
  • codeup
  • C++
  • C
  • 정렬
  • programmers
  • 제코베 JS 100제
  • LeetCode
  • 문자열
  • string
  • 그래프
  • js
  • Level1
  • recursion
  • 다이나믹 프로그래밍
  • tree
  • 백준
  • 수학
  • Level 2

최근 댓글

최근 글

hELLO · Designed By 정상우.
KimMinJun

Coding Note

lower_bound / upper_bound
PS/STL

lower_bound / upper_bound

2022. 2. 3. 18:30

1. lower_bound

  • 이진 탐색 기법이다.
  • 배열이 정렬되어 있어야 한다.
  • 찾으려는 key값이 없으면 key값보다 이상인 가장 작은 정수 값을 찾는다.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	
	vector<int> v = {1, 2, 3, 3, 4, 4, 5, 5};
	
	cout << "lower_bound(2) : " << lower_bound(v.begin(), v.end(), 2) - v.begin() << '\n';
	cout << "lower_bound(4) : " << lower_bound(v.begin(), v.end(), 4) - v.begin() << '\n';
	cout << "lower_bound(5) : " << lower_bound(v.begin(), v.end(), 5) - v.begin() << '\n';
	
	return 0;
}

 

lower_bound는 key값보다 큰 수 중에서 가장 작은 수의 iterator를 반환한다.

따라서 그냥 출력하면 위치를 알 수 없고, 벡터일 경우는 begin() iterator를 빼주어야 해당하는 인덱스를 구할 수 있다.

만약 배열일 경우 배열의 이름을 빼주면 된다.

 

 

2. upper_bound

  • 이진 탐색 기법이다.
  • 배열이 정렬되어 있어야 한다.
  • key값을 초과하는 가장 첫 번째 원소의 위치를 구한다.

 

lower_bound와 사용법은 같다.

아래는 lower_bound와 똑같은 예시이다.

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

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	
	vector<int> v = {1, 2, 3, 3, 4, 4, 5, 5};
	
	cout << "upper_bound(2) : " << upper_bound(v.begin(), v.end(), 2) - v.begin() << '\n';
	cout << "upper_bound(4) : " << upper_bound(v.begin(), v.end(), 4) - v.begin() << '\n';
	cout << "upper_bound(5) : " << upper_bound(v.begin(), v.end(), 5) - v.begin() << '\n';
	
	return 0;
}

 

 

벡터에 5보다 큰 수는 없으므로 벡터의 마지막 원소 다음의 iterator, 즉 end() iterator를 반환한다.

저작자표시

'PS > STL' 카테고리의 다른 글

set  (0) 2022.01.30
sort / stable_sort  (0) 2022.01.30
    'PS/STL' 카테고리의 다른 글
    • set
    • sort / stable_sort
    KimMinJun
    KimMinJun

    티스토리툴바