Shorening code

1) Type names
Using the command typedef it is possible to give a shoreter 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

long long a = 123456789;
long long b = 987654321;
cout << a*b <<"\n";

ll a = 123456789;
ll b = 987654321;
cout << a*b <<"\n";

The command typedef can also be user with more comple types

typedef vector<int> vi;
typedef pair<int,int> pi;

2) 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

#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 shortened as follow

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 shoren loops and other structures.

#define REP(i,a,b) for (int i=a; i<b; i++)
#define SQ(a) (a)*(a);

Mathematics

Sum, Set, Logic, Functions, Logarithms

+ Recent posts