C++ Templates

C++ Templates

Use these templates in the coding round if C++ is allowed.

Basic input-output

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;
    cout << n << "\n";
    return 0;
}

Array input

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; i++) cin >> a[i];

    for (int x : a) cout << x << " ";
    return 0;
}

String input

For single word:

string s;
cin >> s;

For full line with spaces:

string s;
getline(cin, s);

If getline comes after cin, consume newline:

cin.ignore();
getline(cin, s);

Prime check

bool isPrime(int n) {
    if (n < 2) return false;
    if (n == 2) return true;
    if (n % 2 == 0) return false;
    for (int i = 3; i * i <= n; i += 2) {
        if (n % i == 0) return false;
    }
    return true;
}

GCD and LCM

int gcd(int a, int b) {
    while (b != 0) {
        int r = a % b;
        a = b;
        b = r;
    }
    return a;
}

long long lcm(int a, int b) {
    return 1LL * a / gcd(a, b) * b;
}

Frequency map

unordered_map<int, int> freq;
for (int x : a) {
    freq[x]++;
}

For characters:

vector<int> count(256, 0);
for (char ch : s) {
    count[(unsigned char)ch]++;
}

Reverse string

reverse(s.begin(), s.end());

Sort array

sort(a.begin(), a.end());

Two pointers

int left = 0, right = n - 1;
while (left < right) {
    int sum = a[left] + a[right];
    if (sum == target) {
        cout << "YES\n";
        return 0;
    } else if (sum < target) {
        left++;
    } else {
        right--;
    }
}
cout << "NO\n";