Member-only story

10 STL tricks in C++ to ace your interviews

Pratik Rai
2 min readSep 4, 2024

--

Before we proceed with the tricks, let me introduce the most used STL(Standard Template Library) methods..

a) Vector
b) Set
c) Map
d) sort,swap,reverse etc

Let’s look into the basic implementation of these:

// vector
vector<int> array2

//map
map<int,int> mp;
unordered_map<int,int> um;

//sort
sort(array2.begin(),array2.end())

//set
set<int> st;
unordered_set<int> us;

1. Sort function using comparator

vector<int> ans;
// using a lambda function to sort the vector in descending order``
sort(ans.begin(),ans.end(),[](int a , int b){
return b < a;
});

// without lambda function
bool compare(int a , int b){
return b < a ;
}
sort(ans.begin(),ans.end(),compare);

// normal sort function -> sorts in ascending order
sort(ans.begin(),ans.end());

2. Find sum of a vector using accumulate

vector<int> ans;
int sum = accumulate(ans.begin(),ans.end(),0);

3. Find the maximum and minimum element in a vector

vector<int> ans;
int max = *max_element(ans.begin(),ans.end());
int min = *min_element(ans.begin(),ans.end());

--

--

No responses yet