DEV Community

Cover image for C++ STL in a Nutshell
Debjoty Mitra
Debjoty Mitra

Posted on

C++ STL in a Nutshell

I had written these codes as a note when I was learning STL for competitive programming. For better understanding, try to read the comments written with codes.

Pair

pair <int,string> pr;
pr = make_pair(2,"string"); // Initializing Method 1
pr = {2,"Hello"}; // Initializing Method 2 
pair <int,string> &pr2 = pr; // Used Reference // Not copy
pr.first = 10; // Initializing Method 3

pii pairArray[3]; // Array of Pairs
fo(i,3) cin>>pairArray[i].first>>pairArray[i].second;
swap(pairArray[0],pairArray[2]);
fo(i,3) cout<<pairArray[i].first<<" "<<pairArray[i].second<<endl;
Enter fullscreen mode Exit fullscreen mode

Vector

vector <int> v(5,3); // 3 3 3 3 3
v.push_back(1); // O(1) // 3 3 3 3 3 1
v.pop_back(); // O(1) // 3 3 3 3 3

vector <int> v1 = v; // O(n) // Try to pass by ref in fuction call
vector <int> &v1 = v; // Used Reference // Not copy
v[0] = 200;
cout<<v1[0]; // 200

vector <pair<int,int>> vp = {{1,2},{3,4},{5,6}};
fo(i,3) cout<<vp[i].first<<" "<<vp[i].second<<endl;

vector<vector<int>> vec(n, vector<int> (m, 0));
Enter fullscreen mode Exit fullscreen mode

Set

// Stores in sorted order
set <string> st;
s.insert("A") // Initializing
auto it = s.find("A") // Returns an iterator
if(it!=s.end()) s.erase(it); // Erase takes an iterator
s.erase("A");

// unordered_set
// Not sorted
unordered_set <int> st;
st.insert(100); // O(1)
auto it = st.find(100); // O(1)
Enter fullscreen mode Exit fullscreen mode

Map

// Map - Sorted acording to key
// Unordered map - Not sorted
// Uses Red–black tree to store data
// Map is vector of pairs

map <int, string> mis;
mis[3] = "a"; // O(log(n)) // Insertion method 1
mis.insert({2,"b"}); // Insertion method 2
for(auto it:mis) cout<<it.first<<" "<<it.second<<endl;

auto it = mis.find(3); // O(log(n))
if(it == mis.end()) cout<<"Not available";
else cout<<(*it).second;

map <string,string> mss;
mss["abc"] = "abc" // O(s.size()*log(n))

// Unordered Map - Not Sorted
// Uses hash table
// Any that can be compared, can be used in map
// Pair can't be used in unordered_map
unordered_map <int,int> mp;
mp[3] = 3;
mp.insert({1,1});
mp[2] = 2;
for(auto x:mp){
    cout<<x.first<<" "<<x.second<<endl;
}
cout<<mp[4]<<endl;
//Output
// 2 2
// 1 1
// 3 3
// 0
Enter fullscreen mode Exit fullscreen mode

Stack

// LIFO - Last in Fast out
// Accessable - Size and Top Element
// Operation - Push, Pop, See

stack <int> stk;
stk.push(1);
while(!stk.empty()){
        cout<<stk.top()<<endl;
        stk.pop();
}
Enter fullscreen mode Exit fullscreen mode

Queue

// FIFO - First in First out
// Operation - Push, Pop, See
Enter fullscreen mode Exit fullscreen mode

Top comments (0)