# Hidden tricks of C++ related to STL

C++Server Side ProgrammingProgramming

Here we will see some hidden tricks of C++ related to STL.

Assign value of pairs using braces ‘{}’. We can use them to assign into tuples also.

pair<int, int> my_pair = make_pair(10, 20);
pair<int, int> my_pair2 = { 10, 20 }; //using braces
pair<int, <char, int> > my_pair3 = { 10, { 'A', 20 } }; //complex pair

Sometimes we do not remember to include lots of headers, or sometimes we forget the names of the headers, in that time we can follow this trick to include all headers.

#include <bits/stdc++.h>

C++ has inbuilt GCD function. That function is not so popular so we do not know about it. The function can be used like below −

__gcd(a, b)

C++ has to_string() function to convert different datatypes into strings. Suppose we want to make one integer to string or one float to string, we can use this function.

float x = 2.3654;
string str = to_string(x);

Similarly to do the reverse task, that is convert from string to integer, we have stoi() function.

string num = “256”;
int x = stoi(num);

If we declare some variables outside of any function (global variables) then they will be static, and their default values will be 0.

If we declare an array normally, then the value will be some garbage value. To declare an array with all 0 elements, then the declaration will be like below −

int arr[10] = {};

We can assign a whole array with some predefined values using the memset function. If we want to initialize the array with value 5, then all elements will hold 5. We can do by writing these lines −

int arr[10];
memset(arr, 5, sizeof(arr));
Published on 20-Aug-2019 07:07:31