Profile photo for Ashish Gupta

My favorite C++ “hacks” are:

  • Getting rid of “includes”: Just use
    #include <bits/stdc++.h>
  • Useful inbuilt functions:
    • __gcd(a, b): Returns the [math]GCD[/math] of [math]a[/math] and [math]b[/math]
    • __builtin_popcount(x) : Returns the number of set bits in [math]x[/math]
  • Initializer Lists: These make STL containers easy to initialize, for eg:
    • vector<int> odd_nos = {1, 3, 5, 7, 9};
    • pair<int, string> p = {1, “Hi”}; //Equiv. to p=make_pair(1, "Hi")
    • map<int, string> m = { {1, “This”}, {2, “is”}, {3, “awesome”} };
  • Finding min and max of multiple variables:
  1. //Long Way: 
  2.  
  3. int max_of_3 = max(a, max(b, c)); 
  4. int max_of_4 = max(max(a, b), max(c, d)); 
  5.  
  6. //Easier Way - Can be extended to any number of variables: 
  7.  
  8. int max_of_3 = max({a, b, c}); 
  9. int max_of_4 = max({a, b, c, d}); 
  • Range-based for loops: Makes it much simpler to iterate through containers.
  1. //Old Way: 
  2. for(auto it=container.begin(), it!=container.end(); it++) 
  3. cout<<*it<<" "; 
  4.  
  5. //Alternatively: 
  6. for(int i=0;i<container.size();i++) //If the container is a vector 
  7. cout<<container[i]<<" "; 
  8.  
  9. //Easier Way: 
  10. for(auto &it:container) //Using & also allows us to modify the elements 
  11. cout<<it<<" "; 
  • Tie and Swap:
    • Tie makes it easier to initialize multiple variables in a single line
  1. //Initializes a with -1, b with 1, etc 
  2. tie(a, b, c, d) = make_tuple(-1, 1, -2, 2); 
    • Swap enables swapping of variables, and even containers with a single statement
  1. //x, y can be two integers, or two vectors, or any two containers 
  2. swap(x, y); 
  • Macros:
    • If you are tired of typing some statement like push_back again and again, you can just use #define pb push_back , and type pb in your code.
    • Getting the name of the argument in macro using #, and using it to debug your program:
  1. #define trace(x) cerr<<#x<<": "<<x<<" "<<endl; 
  2.  
  3. int main() 
  4. { 
  5. int a=5; 
  6. trace(a); //prints: "a: 5" to stderr stream  
  7. } 
  • Variadic Function Templates:
    • C++ allows templates with variable number of arguments. If you are tired of writing trace1, trace2, trace3, etc for different number of variables you want to print in a line, then you can read about Variadic Functions Templates here.
    • Code for debugging variable number of parameters: Here.
View 1 other answer to this question
About · Careers · Privacy · Terms · Contact · Languages · Your Ad Choices · Press ·
© Quora, Inc. 2025