[C/C++] upper_bound() & lower_bound()

Onam Kwon·2022년 12월 8일
0

C/C++

목록 보기
11/12

upper_bound & lower_bound

  • lower_bound(): 전달인자로 넘겨주는 값 이상인 값중 제일 작은값의 이터레이터 리턴.
  • upper_bound(): 전달인자로 넘겨주는 값을 초과하는 값중 제일 작은값의 이터레이터 리턴.
  • 아래 예시.

🔽main.cpp🔽

#include <vector>
#include <iostream>

using namespace std;

int main() {

    vector<int> v;
    v = {10,20,30,30,40};

    cout<<"Vector contains: ";
    for(const auto &item: v) {
        cout<<item<<" ";
    } cout<<endl;

    /**
     * vector<int>::iterator lower, upper;
     * lower_bound() returns the iterator that is equal or greater than argument(smallest).
     * 전달인자 보다 이상인값의 이터레이터 리턴.
     */
    auto lower = lower_bound(v.begin(), v.end(), 30);
    cout<<"lower_bound(30) in position at: "<<lower-v.begin()<<endl;

    /**
     * upper_bound() returns the iterator that is greater than argument(smallest).
     * 전달인자 보다 초과하는 값의 이터레이터 리턴.
     */
    auto upper = upper_bound(v.begin(), v.end(), 30);
    cout<<"upper_bound(30) in position at: "<<upper-v.begin()<<endl<<endl;
    
    lower = lower_bound(v.begin(), v.end(), 35);
    cout<<"lower_bound(35) in position at: "<<lower-v.begin()<<endl;

    return 0;
}

🔽Output🔽

Vector contains: 10 20 30 30 40 
lower_bound(30) in position at: 2
upper_bound(30) in position at: 4

lower_bound(35) in position at: 4
  • 이 함수를 활용하면 이미 정렬되어 있는 벡터에 새로운 값을 삽입할 때 정렬하면서 삽입할 수 있다.

Github

profile
권오남 / Onam Kwon

0개의 댓글