Anshul_Johri's blog

By Anshul_Johri, 10 months ago, In English

C++ Debug Template 🛠

Simplify variable tracking across functions and loops!

Longer Template (std >= C++11)
Shorter Template, (std >= C++20)

As of now both perform equally well, but my choice? C++20.


Simple Usage

This template supports datatypes such as:

  🔢 Primitive: int, char, bool, long long int etc.

  📚 STL: pair, tuple, vector, set, oset, map, omap, stack, queue, priority_queue, bitset etc.

  📦 Arrays of all datatypes: int arr[], bool arr[], vector<int> adj[] etc.

  🧩 Matrix: int dp[100][200], vector<vector<bool>> vis(100, vector<bool> (200, 0)) etc.

  🕗 Arrays that have been decayed or declared at runtime like int arr[n].

  📝 Rvalue Literals like "Hello", false, 'z', isSafe(i, j), dfs(u).

  🧱 User defined structs / classes like Point, Node.

  🤯 Even nested datatypes like map<string, vector<pair<char, unordered_set<long long>>>> WHATTT;.

Note: For latest updates and a colored stderr version of this template, visit my Github.

Colored Template Preview

How to use it?

Let's say you have different datatypes such as:

Example

You can debug them like this debug(var1, var2, var3, var4, ...);

Example

If you have user defined structs / classes, you just need to make a print() function, and use debug(...) like you do :)

User-Defined struct/class printing.

In instances where array have decayed into pointer, or you declared array at runtime, use debugArr(arr, n);

What is Array Decay?

Note:

  • You don't need to remove debug(...) statements in your code when submitting it.
  • On platforms like Codeforces, there's a macro called ONLINE_JUDGE that's defined, automatically disregarding all your debug statements. This ensures your solution will be accepted unless there's a logical error.

How to Setup?

  • Copy this template into your own templates. The output will be directed to the stderr stream.
  • Alternatively you can make a separate header file and include this into your template
    #ifndef ONLINE_JUDGE
    #include "template.cpp"
    #else
    #define debug(...)
    #define debugArr(...)
    #endif
  • When using it for LeetCode uncomment #define cerr cout and before submitting change #ifndef to #ifdef to ignore debug(...);. For convenience, after changing it, copy it, and keep it pinned in your clipboard for repetitive use.

For Complete Beginners who need step by step tutorial (for VS Code), follow these steps:

Steps

If you liked this blog, please upvote it, I'd really be grateful :)

Edit: Looking for something unique and fun? Check out my other blog on How doing CP and GYM are Alike

Full text and comments »

  • Vote: I like it
  • +241
  • Vote: I do not like it