-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathvector.cpp
69 lines (53 loc) · 1.81 KB
/
vector.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
#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<vector>
bool f(int x, int y)//comparator function return true/false declared in global space
{
return x>y;
}
using namespace std;
int main()
{
//C++ STL
vector<int>A={11,2,3,14};
cout<<A[1]<<endl;
sort(A.begin(),A.end());//O(NlogN)
//2,3,11,14
//O(logN) Binary Search
bool present=binary_search(A.begin(),A.end(),3);//true
cout<<present<<endl; // 1
present=binary_search(A.begin(),A.end(),4);//false
cout<<present<<endl; //0
A.push_back(100);
present=binary_search(A.begin(),A.end(),100);//true
cout<<present<<endl;//1
A.push_back(100);
A.push_back(100);
A.push_back(100);
A.push_back(100);
A.push_back(123);
//2,3,11,14,100,100,100,100,100,123
/* vector<int>::iterator */ auto it=lower_bound(A.begin(),A.end(),100);//pointing the iterator to the 1st occurence of >= points to 1st 100
/* vector<int>::iterator */auto it2=upper_bound(A.begin(),A.end(),100);//pointing the iterator to the 1st number strictly > than 100 i.e. it points to 123
cout<<*it<< " "<<*it2<<endl;
cout<<it2-it<<endl;//iterators in vectors are random in O(1) time // 9-4=5 //Gives the count of occurence of 100 s
//sorting in descending order
sort(A.begin(),A.end(),f);//overloaded function by passing a comparator function f
//Printing the elements of the vector
/* vector<int>::iterator it3;
for(it3=A.begin();it3!=A.end();it3++)
{
cout<<*it3<<" ";
} */
for(int &x:A)//"&" helps iterating by reference
{
x++;//Now after adding '&' any changes made to x will be applied to particular vector element
}
// All elements will be incremented by 1
for(int &x:A)//"&" helps iterating by reference
{
cout<<x<<" ";
}
cout<<endl;
}