vector v; // empty vector vector v(5); // of size 5, but all 0 vector v(5,1); //all ones
v.push_back(x); v.pop_back(); v.begin() v.end()
sort(startPointer,endPointer) sort(arr, arr + n, greater()); //descending order
Sort a pair based on second element:
bool sortbysecond(const pair <int, int> &a, const pair <int, int> &b) {
return (a.second < b.second);
}
void solve() {
vector<pair<int, int>> arr = {{1, 5}, {1, 4}, {1, 3}, {1, 2}, {1, 1}};
sort(arr.begin(), arr.end(), sortbysecond);
for (ll i = 0 ; i < 5; i++) {
cout << arr[i].first << " :" << arr[i].second << endl;
}
}
pair<int,string> p = {4,"hey"}; p.first=12; p.second="bye";
vector v= {10,15,12,5,20};
auto it=v.begin(); //auto assigns the datatype automatically
it can now be used for iterating just like a normal pointer
unique | sorted | no random access (i.e. use iterators/pointers)
set s; //empty set of integers
set s; //empty set of strings
s.insert(x);
s.insert(x);
s.erase(x);
s.clear()’
Set Iterators
s.begin() //points to the smallest element of the set because set is sorted
s.find(x)
s.erase(it)
s.end() // is the iterator of non-existant element
Searching for an element in SET
s.find(x)==s.end() //not found
s.count(x)==0 //not found
s.count(x); //for set
count(v.begin(),v.end(),x); //for vector
count(str.begin(),str.end(),'y'); // in a string
map<key_dataType, value_dataType>
sorted according to keys ( similar to set) | keys are unique | useful for counting frequencies
m.clear() //clears a map
m[key] - value for the corresponding key - O(logN)
eg:
map<string, double> m;
//insert some values in map
auto it= m.find("aasil");
pair<string, double> p = *it; // { ”aasil”, m[”aasil”] }
if(mp.find(s1)==mp.end()) // a simple condition to check if the key searched is present by searching till the end of the map
Note: if you try to search for a value with a key which is not existing, then it creates the element with the searched key and the value assigned is 0.
->Conventional method: // works for map/set/vector
for (auto it = s.begin() ; it ≠ s.end(); it++)
{
//*it
}
->Shorthand method:
vector v;
for (int x:v){
//x
}
set s;
for(int x:s){
//x
}
map<int ,int> x;
for (pair<int,int> x: v){
//x.first, x.second
}
returns an iterator pointing to the first element in the range [first, last)
Note: In map its key value pair because x.first is key, x.second is value.
Specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue and elements are in nonincreasing order.
priority_queue g ;
Extra:
A shop has objects (key - name , value- price). Get the cheapest
then, set(pair<int,string>)