-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdata_structures.cpp
More file actions
103 lines (81 loc) · 1.99 KB
/
data_structures.cpp
File metadata and controls
103 lines (81 loc) · 1.99 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//STRING
string s;
getline(cin,s); //inputting string
string s1,s2;
s=s1+s2; //Combine strings
string a = s.substr(k,l); //Substring of 's' starting at index 'k' and of length 'l'
//SET
set<int> s;
s.insert(3);
s.insert(2);
s.insert(5);
cout << s.count(3) << "\n"; // 1
cout << s.count(4) << "\n"; // 0
s.erase(3);
s.insert(4);
cout << s.count(3) << "\n"; // 0
cout << s.count(4) << "\n"; // 1
s.count(x); //0 if absent or 1 if present
set<int> s = {2,5,6,8};
cout << s.size() << "\n"; // 4
for (auto x : s) {
cout << x << "\n";
}
//MULTI-SET
multiset<int> s;
s.insert(5);
s.insert(5);
s.insert(5);
cout << s.count(5) << "\n"; // 3
s.erase(5);
cout << s.count(5) << "\n"; // 0
//OR
s.erase(s.find(5));
cout << s.count(5) << "\n"; // 2
//MAP
//syntax for declaration
map<key_data_type, key_value_data_type> m;
//Example
m["monkey"] = 4;
m["banana"] = 3;
m["harpsichord"] = 9;
cout << m["banana"] << "\n"; // 3
//If key is absent, key value is zero by default if requested
map<string,int> m;
cout << m["aybabtu"] << "\n"; // 0
m.count(key); //checks if key is declared (present) or not
m.count("banana"); //true
m.count("subscribe_pewdiepie"); //false
//Iterating through a map
for (auto x : m) {
cout << x.first << " " << x.second << "\n";
}
//ITERATORS
auto it=s.begin(); //OR
set<int>::iterator it=s.begin();
auto it=s.find(x); //returns iterator to the position of 'x', if x not found then return s.end()
//Element nearest to 'x'
auto it = s.lower_bound(x);
if (it == s.begin()) {
cout << *it << "\n";
}
else if (it == s.end()) {
it--;
cout << *it << "\n";
}
else {
int a = *it; it--;
int b = *it;
if (x-b < a-x) cout << b << "\n";
else cout << a << "\n";
}
/*Deques
A deque is like a vector but better in the sense that it can push and pop from back as well as from the front
for example */
deque<int> d;
d.push_back(5); // [5]
d.push_back(2); // [5,2]
d.push_front(3); // [3,5,2]
d.pop_back(); // [3,5]
d.pop_front(); // [5]
// draw back is that its slower then vector