Must-Know C++ tips and tricks for Competitive Programming — Part 1

Seven things that save time in a contest: bits/stdc++.h, endl versus \n, auto, range-based loops, string conversions, cctype, and a code visualizer.

First published on Medium


Note from Author (Dhruv Kothari): Hello readers! This article is part 1 of Must-Know C++ tips and tricks for Competitive Programming. All the opinions expressed in this article represent my own views, which I think are appropriate to keep in mind while doing competitive programming.

Before starting I would recommend you to please check out my previous article on a beginner’s roadmap to start competitive programming — Complete guide to kick-off Competitive Programming!

1. Use <bits/stdc++.h> header file

Let us start with the header file. <bits/stdc++.h> is a most commonly and widely used header file in the competitive programming world. Basically, it is a header file that includes all the standard libraries.

All these libraries are included in <bits/stdc++.h>. We all know that time is very precious in programming contests, hence using this header file would be a clever choice to save a lot of time and avoid mistakes.

Things to keep in mind while using <bits/stdc++.h>

  • This header file contains a lot of header files which might be of no use in your code, which may increase compilation time.
  • It is not the standard header file of the GNU C++ library, hence compilers other than GCC might not be able to compile it. But don’t worry, this won’t happen in most cases 😅😅.

2. "\n" versus endl

For most of us, both sound the same right? But it’s not the case. endl takes more execution time than "\n", which can cause TLE. Here is the reason:

"\n"    // it inserts a new line.
"endl"  // it inserts a new line and flushes the stream.

// So "\n" is a character whereas endl is a manipulator.
// "endl" is equivalent to cout << '\n' << flush;

Try problem UNITGCD: codechef.com/problems/UNITGCD on CodeChef. Using endl in place of "\n" will cause a TLE in the above question.

TIP

Hence to avoid this mistake we can define a macro:

#define endl "\n"

3. auto (keyword)

When I started with STL, iterators were one of the toughest things to understand, as well as declaring-syntax was a difficult job, and maybe the same case is with you. Here’s where auto (keyword) comes into the picture. Before C++ 11, data types were mandatory to be defined during compile-time, but later on the auto keyword was introduced which gave us the freedom to declare a variable at runtime. So we no longer need to define the datatype. This helps us to define iterators very easily.

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

int main()
{
    auto x = 'd';        // data types will be declared at runtime
    auto y = 24;
    auto z = 83.6667;
    auto b = true;

    cout << typeid(x).name() << endl;   // output: c
    cout << typeid(y).name() << endl;   // output: i
    cout << typeid(z).name() << endl;   // output: d
    cout << typeid(b).name() << endl;   // output: b

    return 0;
}

4. Range-based for-loops

Range-based for loops are an upgraded version of traditional for loops. They are quite similar to the for loops which we use in Python. They were introduced in C++ 11. We can easily iterate over vectors, maps, and other STL containers with this for loop and the auto keyword. It’s really comprehensive and powerful.

Syntax

for ( range_declaration : range_expression )

  • range_declaration: here we have to write the data-type of the iterator which is going to iterate through the container. So we can use the auto keyword. It will detect the datatype during runtime.
  • range_expression: we have to mention the container on which we have to iterate.

Also, we can reverse iterate the loop by using boost::adaptors::reverse(v1), which is included in the <boost/range/adaptor/reversed.hpp> header.

#include <bits/stdc++.h>
#include <boost/range/adaptor/reversed.hpp>   // for reversing range based loop
using namespace std;

int main()
{
    string s = "kothariji";
    int y[] = {1, 2, 3, 4, 5, 6, 7, 8};
    int i = 1;
    vector<int> v1{1, 2, 3, 4, 5, 6, 7, 8};

    for (auto x : s)
        cout << x << " ";                     // output: k o t h a r i j i
    for (auto x : y)
        cout << x << " ";                     // output: 1 2 3 4 5 6 7 8
    for (auto x : boost::adaptors::reverse(v1))
        cout << x << " ";                     // output: 8 7 6 5 4 3 2 1

    return 0;
}

5. String to integers and vice versa

Integer to string

  • The to_string() function is used to convert a number into a string. I have listed 2 more ways to convert numbers to a string.
  • For single-digit integer to string:
char c = char(num + 48);   // where num is a single digit integer like 3 or 7.
                           // So char() typecasts {num+48} from ASCII value to char.

String to integer

  • stoi() is the function used for converting a string to an integer. For beginners it might be new, so I included that in this series.
  • For single-digit integer:
int x = int(c) - 48;   // here c is a char like '3' or '7'. So int() typecasts c
                       // and converts it into an ASCII value, and then we subtract
                       // 48 (ASCII of digits starts with 48) to get the integer.

6. isalnum(), isalpha(), isdigit() and many more!

These functions can be found in the header <cctype>.

These functions are very useful in checking whether the character is an uppercase alphabet, lowercase alphabet, a number, and many more. These functions are really very useful while doing competitive programming. Here is the list of a few must-know functions.

1. isalpha( )   // returns a non-zero value if a character is an alphabet, else returns 0
2. isalnum( )   // returns a non-zero value if a character is an alphabet or numeric, else returns 0
3. isupper( )   // returns a non-zero value if a character is an upper-case alphabet, else returns 0
4. islower( )   // returns a non-zero value if a character is a lower-case alphabet, else returns 0
5. isdigit( )   // returns a non-zero value if a character is a numeric digit, else returns 0
6. ispunct( )   // returns a non-zero value if a character is a punctuation character, else returns 0

A few more functions which we use to change the case of alphabet characters.

1. toupper( )   // it is used to convert a lowercase alphabet to an uppercase alphabet
2. tolower( )   // it is used to convert an uppercase alphabet to a lowercase alphabet

7. C++ code visualizer

At the initial stage, we often find that our syntax is correct but the output is wrong, which means there is something wrong with the logic. And sometimes it is very difficult to debug the logical error. In that case, we can use this tool through which we can visualize our code.

Link: pythontutor.com/cpp.html

References

That’s it from this article. Hope you liked this article.

For more such tips and tricks check out my GitHub repo: 30-days-of-code-LinkedIn.

Thank you. See you in the next one!

Part 2 will be released soon.