![]() |
VOOZH | about |
Shortcode is ideal in competitive programming because programs should be written as fast as possible. Because of this, competitive programmers often define shorter names for datatypes and other parts of the code.
We here discuss the method of code shortening in C++ specifically.
Type names
Using the command typedef it is possible to give a shorter name to a datatype.
For example, the name long long is long, so we can define a shorter name ll:
typedef long long ll;
After this, the code
can be shorted as follows:
The command typedef can also be used with more complex types. For example, the following code gives the name vi for a vector of integers and the name pi for a pair that contains two integers,
Macros
Another way to shorten code is to define macros. A macro means that certain strings in the code will be changed before the compilation. In C++, macros are defined using the #define keyword.
For example, we can define the following macros:
#define F first
#define S second
#define PB push_back
#define MP make_pair
After this, the code
v.push_back(make_pair(y1, x1)) ;
v.push_back(make_pair(y2, x2));
int d = v[i].first+v[i].second;
can be shorted as follows
v.PB(MP(y1, x1));
v.PB(MP(y2, x2));
int d = v[i].F+v[i].S;
A macro can also have parameters which makes it possible to shorten loops and others structures. For example, we can define the following macro:
#define REP(i, a, b) for (int i=a; i<=b; i++)
After this, the code
for (int i=1; i<=n; i++){
search(i);
}
can be shortened as follows:
REP(i, 1, n){
search(i);
}
A version of template given below
This can be use in competitive programming for faster coding.