Skip to content
Related Articles

Related Articles

Some useful C++ tricks for beginners in Competitive Programming

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 06 Aug, 2022

Here are some of the basic C++ tricks that every beginner in Competitive Programming should follow for increased speed. However, competitive programming can only be mastered with time and lots of practice. These tricks will just help you to save a little time during the contests which sometimes matters a lot. 


  • Using the auto keyword to declare data types can save a lot of time during programming contests. 

    When a variable is defined as auto, the compiler can be determining the datatype on its own. 

auto a = 100; // a will become 'int'
auto b = 1LL; // b will become 'long long'
auto c = 1.0; // c will become 'double'
auto d = "variable"; // d will become 'const char*'
  • The watch macro is one of the most useful tricks ever. 
#define watch(x) cout << (#x) << " is " << (x) << endl
  • If you’re debugging your code, watch(variable); will print the name of the variable and its value. (It’s possible because it’s build in preprocessing time.)
  • Using typedef’s can save a lot of time of yours which you might spend re-writing the same snippet again and again. 
typedef long long ll;
typedef pair w;
typedef vector va;
typedef vector vb;
typedef vector vc;

Use of C++ STL

The C++ STL is a very rich library consisting of useful functions, which are super useful and time-saving during contests. For using these functions you need to include a header file. 

#include <algorithm>

We are going to discuss the most commonly used STL algorithmic functions below:-

// for binary search in containers like vector (let target element=6)
binary_search(v.begin(), v.end(), 6); 
// return 1 or 0 as present or not

// max/min of two numbers
ans = max(a,b);
ans = min(a,b);

// max/min of three numbers
ans = max(a,max(b,c));
ans = min(a, min(b,c));

// swap two numbers

// reverse containers like vectors, strings
reverse(v.begin(), v.end());

// rotate containers like vector, strings by n position
rotate(v.begin(), v.begin()+n, v.end());

// sort arrays of size n
sort(arr, arr+n);

// sort containers like vector, strings(based on intro sort)
sort(v.begin(), v.end());
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!