DEV Community

Cover image for C++ Productivity Hacks
Jeevan Chandra Joshi
Jeevan Chandra Joshi

Posted on

C++ Productivity Hacks

1. Master Header File

#include <bits/stdc++.h>
Enter fullscreen mode Exit fullscreen mode

2. Faster I/O Operations

ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
Enter fullscreen mode Exit fullscreen mode

3. Macros for Debugging

#define deb(x) cout << #x << " : " << x << "\n"
Enter fullscreen mode Exit fullscreen mode

4. Number of Digits

int number = 12345;
int digits = floor(log10(number) + 1); // 5
Enter fullscreen mode Exit fullscreen mode

5. Swap Two Numbers

int a = 10;
int b = 20;
swap(a, b); // 20 10
Enter fullscreen mode Exit fullscreen mode

6. Number of Set Bits

int n = 15;
int setBit = __builtin_popcount(n); // 4
Enter fullscreen mode Exit fullscreen mode

7. Auto Keyword

vector<int> v{1, 2, 3, 4, 5};
for (auto x : v)
  cout << x << " "; // 1 2 3 4 5
Enter fullscreen mode Exit fullscreen mode

8. Inbuilt GCD Function

int x = 12;
int y = 16;
int gcd = __gcd(x, y); // 4
Enter fullscreen mode Exit fullscreen mode

9. Lambda Function

auto add = [](int x, int y) {
  return x + y;
};
int sum = add(10, 20); // 30
Enter fullscreen mode Exit fullscreen mode

10. Accumulate Function

int sum = 10;
int arr[] = {20, 30, 40};
sum = accumulate(arr, arr + 3, sum); // 100
Enter fullscreen mode Exit fullscreen mode

Tip: Use "\n" instead of endl;

Top comments (2)

Collapse
 
sandordargo profile image
Sandor Dargo

In my opinion it would be worth explaining why something is considered a productivity trick at what it does. Plus, prepend std:: in case it's needed, because your readers might not know that std::accumulate is part of the <numeric> header.

A few comments without wanting to be complete here.

  1. In production environment never ever use <bits/stdc++.h>. It will blow the size of your software as it includes whatever, plus it's not portable between different compilers.

  2. No. In 2021 you barely need macros. Start with this.

6.-8. In C++ there is no built-in __builtin_popcount nor __gcd. Some compilers might or might not provide them. But at least std::gcd is provided by the the standard library in <numeric> header.

+1) Productivity trick. Understand what you use and why you use it, that's the only thing that will boost your productivity in the long run.

Collapse
 
aminpial profile image
Amin Pial

Please don't get me wrong. But let me be honest with you. This is not an "hack" rather the "worst possible software engineering practice". Yeah, "hacking" is an "anti-pattern" in SWE itself. Please avoid these type "magic numbers and library call". This is okay for some fancy competitive programming environment, not in Software Engineering.
Cheers!