Open In App

Some useful C++ tricks for beginners in Competitive Programming

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. 

 

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*'
#define watch(x) cout << (#x) << " is " << (x) << endl
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
swap(a,b);

// 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());
Article Tags :