1#include <bits/stdc++.h>
2#include <iostream>
3#include <vector>
4#include <algorithm>
5
6using namespace std;
7//defining the comparator function returns true or false
8//not for binary search..
9bool f(int x, int y){
10 return x>y; //for decreasing order
11}
12
13int main() {
14
15 vector<int> A ={ 11,2,3,14 };
16 cout<<A[1]<<endl;//2
17
18 sort(A.begin(), A.end()); // sort in order to perform binary search
19 cout<<A[1]<<endl;//3 after sorting
20
21 bool present = binary_search(A.begin(), A.end(), 3);
22 cout<<present<<endl;//will return true
23
24 present = binary_search(A.begin(), A.end(), 5);
25 cout<<present<<endl;//will return false
26
27 A.push_back(100);//inserting new element from end
28
29 present = binary_search(A.begin(), A.end(), 100);
30 cout<<present<<endl;
31
32 A.push_back(100);
33 A.push_back(100);
34 A.push_back(100);
35 A.push_back(121);
36
37 //give me the iterator pointing to first element >= 100
38 vector<int>::iterator it = lower_bound(A.begin(), A.end(), 100);
39 //you can also use auto as c++ will see that a lower_bound is performed
40 //and it will figur it out that it is an iterator of vector<int>
41 //auto it = lower_bound(A.begin(), A.end(), 100);
42 //auto it2 = upper_bound(A.begin(), A.end(), 100);
43
44
45
46 //give me an iterator pointing to first element >100
47 vector<int>::iterator it2 = upper_bound(A.begin(), A.end(), 100);
48
49 //print the content of it and it2
50 cout<<*it<<" "<<*it2<<endl;
51
52 //give me the number of hundreds(100)
53 cout<<it2-it<<endl; //4 it subtracts the indices
54
55
56 //soritng the vector in reverse order
57 //use method overloading with sort by passing a comparator function
58 //to control the ordering
59 sort(A.begin(), A.end(), f);
60
61 //now print the sorted vector using iterator
62 vector<int>::iterator it3;
63
64 for (it3 =A.begin(); it3!= A.end(); it3++){
65 cout<<*it3<<" ";
66 }
67 cout<<endl;
68
69 //A shorter code for the above will be
70 for(int x: A){
71 //x++ wont change the vector content it will only print the changed one
72 cout<<x<<" ";
73 }
74 cout<<endl;
75
76 //to change the vector content while iterating
77 //iterate it by referance by using &x
78 for(int &x: A){
79 x++;
80 cout<<x<<" ";
81 }
82 cout<<endl;
83
84 return 0;
85}