이진탐색을 사용하여 탐색하여 있으면 True, 없으면 False를 return.
(탐색을 진행할 배열 혹은 벡터는 오름차순 정렬되어 있어야 함)
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int a[10] = {17, 25, 67, 84, 90, 30, 55, 6, 9, 28};
sort(a, a + 10);
cout << "값 55: ";
if(binary_search(a, a+10, 55)) cout << "찾았습니다." << endl;
else cout << "찾지 못했습니다." << endl;
cout << "값 80: ";
if(binary_search(a, a+10, 80)) cout << "찾았습니다." << endl;
else cout << "찾지 못했습니다." << endl;
return 0;
}
lower_bound는 주어진 key 값보다 같거나 큰
가 몇 번째
에 나오는지
upper_bound는 주어진 key 값보다 큰 숫자
가 몇 번째
값
(탐색을 진행할 배열 혹은 벡터는 오름차순 정렬되어 있어야 함)
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
vector<int> arr = { 10,20,30,40,50 };
cout << "lower_bound(25) : " << lower_bound(arr.begin(), arr.end(), 25) - arr.begin() << endl;
cout << "upper_bound(25) : " << upper_bound(arr.begin(), arr.end(), 25) - arr.begin() << endl;
// 결과 -> lower_bound(25) : 2
// 결과 -> upper_bound(25) : 2
return 0;
}
시작점(begin)
부터 지정범위(end)
까지 어떤 객체(42)
로 지정하는 함수
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
vector<int> arr;
fill(arr.begin(), arr.end(), 42);
return 0;
}
매개변수 x와 y의 값
을 바꾸는 것
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int a = 3, b = 5;
cout << "a: " << a << ", b: " << b << endl;
// a: 3, b: 5
swap(a, b);
cout << "a: " << a << ", b: " << b << endl;
// a: 5, b: 3
return 0;
}
임의의 시작범위(A.begin())
부터 끝 범위(A.end())
까지의 최대 or 최소 iterator
을 return
--> value를 return하고 싶으면 pointer를 return!!
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
vector<int> arr = {3, 1, 4, 2, 5, 6};
cout << "최대: " << *max_element(arr.begin(), arr.end()) << endl;
cout << "최소: " << *min_element(arr.begin(), arr.end()) << endl;
// 최대: 6
// 최소: 1
return 0;
}
임의의 시작범위(A.begin())
부터 끝 범위(A.end())
까지 배열을 뒤집음
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
vector<int> arr = { 1, 2, 3, 4, 5, 6 };
for (int i : arr) cout << i << " ";
cout << endl;
// 1, 2, 3, 4, 5, 6
reverse(arr.begin(), arr.end());
for (int i : arr) cout << i << " " << endl;
cout << endl;
// 6, 5, 4, 3, 2, 1
return 0;
}
임의의 시작범위(A.begin())
부터 끝범위(A.end())
까지 shift만큼 왼쪽
이동
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
vector<int> arr = { 1, 2, 3, 4, 5, 6 };
for (int i : arr) cout << i << " ";
cout << endl;
// 1, 2, 3, 4, 5, 6
rotate(arr.begin(), arr.begin()+3, arr.end());
for (int i : arr) cout << i << " " << endl;
cout << endl;
// 4, 5, 6, 1, 2, 3
return 0;
}
배열의 시작(A.begin())
부터 끝(A.end())
까지 오름차순
정렬
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
vector<int> arr = {3, 1, 4, 2, 6, 5};
sort(arr.begin(), arr.end());
for (int i : arr) cout << i << " ";
cout << endl;
// 1, 2, 3, 4, 5, 6
reutrn 0;
}