알고리즘
[C++] set::lower_bound() 함수
lewns2
2021. 7. 25. 00:48
원문 : https://www.geeksforgeeks.org/set-lower_bound-function-in-c-stl/
set lower_bound() function in C++ STL - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
set::lower_bound()은 C++ STL 내장함수이다.
매개 변수에 전달된 k와 동일한 컨테이너의 요소를 가리키는 반복자를 리턴한다.
☞ key가 set 배열안에 있어! → key값에 해당하는 요소를 반환한다.
set 컨테이너에 k가 없는 경우, 함수는 k보다 큰 다음 요소를 가리키는 반복자를 리턴한다.
☞key가 set 배열 안에 없어! → set 배열 중에 key보다 큰 요소 중 가장 작은 요소를 반환하다.
예시를 살펴보자!
Syntax:
set_name.lower_bound(key)
CODE
// CPP program to demonstrate the
// set::lower_bound() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
set<int> s;
// Function to insert elements
// in the set container
s.insert(1);
s.insert(4);
s.insert(2);
s.insert(5);
s.insert(6);
cout << "The set elements are: ";
for (auto it = s.begin(); it != s.end(); it++)
cout << *it << " ";
// when 2 is present
auto it = s.lower_bound(2);
if (it != s.end()) {
cout << "\nThe lower bound of key 2 is ";
cout << (*it) << endl;
}
else
cout << "The element entered is larger than the "
"greatest element in the set"
<< endl;
// when 3 is not present
// points to next greater after 3
it = s.lower_bound(3);
if (it != s.end()) {
cout << "The lower bound of key 3 is ";
cout << (*it) << endl;
}
else
cout << "The element entered is larger than the "
"greatest element in the set"
<< endl;
// when 8 exceeds the max element in set
it = s.lower_bound(8);
if (it != s.end()) {
cout << "The lower bound of key 8 is ";
cout << (*it) << endl;
}
else
cout << "The element is larger than the greatest "
"element in the set"
<< endl;
return 0;
}
Output:
The set elements are: 1 2 4 5 6
The lower bound of key 2 is 2
The lower bound of key 3 is 4
The element is larger than the greatest element in the set
해석:
1. Key = 2인 경우
→ '2'는 set 배열 안에 있으므로, '2'를 반환한다.
2. Key = 3인 경우
→ '3'은 set 컨테이너 안에 없으므로, '3'보다 큰 원소 중 가장 작은 '4'를 반환한다.
728x90
반응형