-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathstl_02_binarysearch_lowerbound_upperbound.cpp
80 lines (60 loc) · 2.48 KB
/
stl_02_binarysearch_lowerbound_upperbound.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// code_report
// https://youtu.be/rXuqUtifDU8
#include <vector>
#include <algorithm>
#include <iostream>
#include <string>
#include <functional>
#include <iterator>
using namespace std;
void example1 () {
vector<int> v = { 1, 3, 5, 7 };
cout << (binary_search (v.begin (), v.end (), 3) ? "Found" : "Not Found") << endl; // outputs Found
cout << (binary_search (v.begin (), v.end (), 4) ? "Found" : "Not Found") << endl; // outputs Not Found
}
void example2 () {
vector<int> v = { 7, 5, 3, 1 };
cout << (binary_search (v.begin (), v.end (), 3, greater<int> ()) ? "Found" : "Not Found") << endl; // outputs Found
cout << (binary_search (v.begin (), v.end (), 4, greater<int> ()) ? "Found" : "Not Found") << endl; // outputs Not Found
}
void example3 () {
vector<int> v = { 1, 3, 3, 5, 7 };
auto it = lower_bound (v.begin (), v.end (), 3);
auto it2 = lower_bound (v.begin (), v.end (), 4);
auto it3 = lower_bound (v.begin (), v.end (), 8);
cout << (it != v.end () ? to_string (*it) : "Not Found") << endl; // outputs 3
cout << (it2 != v.end () ? to_string (*it2) : "Not Found") << endl; // outputs 5
cout << (it3 != v.end () ? to_string (*it3) : "Not Found") << endl; // outputs Not Found
cout << distance (v.begin (), it) << endl; // outputs 1
}
void example4 () {
vector<int> v = { 1, 3, 3, 5, 7 };
auto it = upper_bound (v.begin (), v.end (), 3);
auto it2 = upper_bound (v.begin (), v.end (), 4);
auto it3 = upper_bound (v.begin (), v.end (), 8);
cout << (it != v.end () ? to_string (*it) : "Not Found") << endl; // outputs 5
cout << (it2 != v.end () ? to_string (*it2) : "Not Found") << endl; // outputs 5
cout << (it3 != v.end () ? to_string (*it3) : "Not Found") << endl; // outputs Not Found
}
template<typename ForwardIterator, typename T>
ForwardIterator first_less_than (ForwardIterator first, ForwardIterator last, T value) {
auto it = std::lower_bound (first, last, value);
return (it == first ? last : --it);
}
void example5 () {
vector<int> v = { 1, 3, 3, 5, 7 };
auto it = first_less_than (v.begin (), v.end (), 3);
auto it2 = first_less_than (v.begin (), v.end (), 4);
auto it3 = first_less_than (v.begin (), v.end (), 8);
cout << (it != v.end () ? to_string (*it) : "Not Found") << endl; // outputs 1
cout << (it2 != v.end () ? to_string (*it2) : "Not Found") << endl; // outputs 3
cout << (it3 != v.end () ? to_string (*it3) : "Not Found") << endl; // outputs 7
}
int main () {
example1 ();
example2 ();
example3 ();
example4 ();
example5 ();
return 0;
}