CPP cheatsheet for LeetCode Practice, Competitive programming

Photo by Pawel Czerwinski on Unsplash

CPP initial code


// C++ program to construct a Binary Tree from parent array
#include<bits/stdc++.h>
using namespace std;

Sort an Array in CPP/C++ using sort()

Sort in Ascending order

    vector<int> arr = {34, 12, 1, 78, 90, 23};
int len = arr.size();

// ascending order
sort(arr.begin(), arr.end());

for (int i = 0; i < len; i++)
{
cout << " " << arr[i]; // 1 12 23 34 78 90
}

2D Vector Declaration

std::vector<std::vector<int>> twoDVector(rows, std::vector<int>(columns, initialValue));

Sort in Descending order

vector<int> arr = {34, 12, 1, 78, 90, 23};
int len = arr.size();

// descending order
sort(arr.begin(), arr.end(),greater<int>());

for (int i = 0; i < len; i++)
{
cout << " " << arr[i]; // 1 12 23 34 78 90
}

// greater<int>() compares two arguments and returns true when the first one is
// greater than second one

Use Lambda function

    vector<pair<int,int>> arr = {{0,30},{5,10},{15,20},{6,34},{3,23}};
int len = arr.size();

// use lambda function sort a pair in descending order with respect to
// first element
sort(arr.begin(), arr.end(), [](pair<int,int> &a, pair<int,int> &b)
{ return a.first > b.first; });

for (int i = 0; i < len; i++)
{
cout << "\n"<<arr[i].first<<" "<<arr[i].second;
}

// Output -
15 20
6 34
5 10
3 23
0 30

Use user-define function / comparator

bool comparator(pair<int, int> a, pair<int, int> b)
{
return a.first > b.first;
}

int main()
{
vector<pair<int, int>> arr = {{0, 30}, {5, 10}, {15, 20}, {6, 34}, {3, 23}};
int len = arr.size();
// use comparator function
sort(arr.begin(), arr.end(), comparator);

for (int i = 0; i < len; i++)
{
cout << "\n"
<< arr[i].first << " " << arr[i].second;
}

return 0;
}

// output
15 20
6 34
5 10
3 23
0 30

Unordered Map

  1. Store key-value pair.
  2. unordered_map are not sorted.
  3. Fast access to individual element using keys — constant average time complexity.
  4. unordered_map faster than map.

at() vs operator[] access

at()

Parameters

  1. key — the key of the element to find

Return Value

  1. the reference to the mapped value

Exception

  1. out_of_range if the unordered_map does not contain the element with specified key

Operator[]

Return Value

  1. Returns the default value if the key not found in the map.

Unordered Set

Methods of Unorder Set

count

  1. returns 1 if element is present
  2. otherwise returns 0.
unordered_set<int> used;

used.insert(3);
used.insert(4);
used.insert(3);

used.count(3)// 1
used.count(5) // 0

insert(item) inserts an element to the unordered set
count() returns 1 if the specified value exists and 0 if it doesn't
find(value) returns the iterator to the element with the specified value
size() returns the number of unique elements
empty() returns true if the unordered set is empty
erase(value) removes elements with the specified value
clear() removes all elements

Convert a vector to unordered_set

    std::unordered_set<int> set(input.begin(), input.end());

Set in CPP

TreeNode

 * struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };

Linked List Node

 * struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };

String in CPP

string:substr(pos,len)

 string dream= "Alok";
cout<<dream.substr(1,2); // lo

Create a string from a char of given length

int main() {
char c='a';
string s(2,c);
cout<<s; //aa
}

How to convert an int to a string in c++ using to_string() method

#include <iostream>
using namespace std;

int main() {

int age = 20;

string age_as_string = to_string(age);

cout << "The user is " + age_as_string + " years old";
// The user is 20 years old

return 0;

}

Convert a string into an integer

int main() {

string s = "26";
int p = stoi(s);
int sum = 23;

cout<<sum+p; // 49

}

Get bitset of a number in CPP

Compare a character with space character in CPP.

// c == ' ' -- Note here we use single quotes not double quotes
if(isspace(c))
{
}

--

--