Skip to content
CCC Python Course

C++ bridge (optional)

Module
M7.14
Lesson
1 of 1
Reading time
4 min

In this lesson

  • Read C++ syntax and recognise structures you know from Python.
  • Translate Python patterns to their C++ equivalents.
  • Use templates and the standard library to write concise C++ code.
  • Understand when C++ is faster and when the speed difference matters.

You have written all your CCC solutions in Python. If you choose, you can write in C++ instead. C++ is faster and gives you more control over memory. But it is also more complex, and the speed gain is not always worth the extra effort.

This lesson teaches you to read C++ and translate your Python code. It does not teach you to be fluent in C++. It teaches you to see Python patterns in C++ code and do the reverse.

From Python to C++

Python and C++ share the same algorithmic ideas. A Python list becomes a C++ vector. A Python dictionary becomes a C++ map. A Python function becomes a C++ function. The differences are syntax and type annotations.

Here is a Python program that reads integers and computes their sum:

examples/cpp_vs_python.py
import sys

def main() -> None:    data = sys.stdin.read().split()    n = int(data[0])    total = 0    for i in range(1, n + 1):        total += int(data[i])    sys.stdout.write(f"{total}\n")

if __name__ == "__main__":    main()

Input

4
3 1 4 1

Output

9
Read N integers and print their sum

The equivalent C++ program:

#include <iostream>#include <vector>using namespace std;
int main() {    int n;    cin >> n;    int total = 0;    for (int i = 0; i < n; i++) {        int x;        cin >> x;        total += x;    }    cout << total << "\n";    return 0;}

Both programs do the same thing. The C++ version reads from cin instead of parsing a string. It declares types explicitly. The loop syntax is different. But the logic is identical.

Common patterns

Reading input: Python uses sys.stdin.read().split() or input(). C++ uses cin >>. Both fill variables with input.

Lists and arrays: Python has list and array. C++ has vector<int>. Both grow dynamically.

Dictionaries and maps: Python has dict. C++ has map<key_type, value_type>. Both store key-value pairs.

Sorting: Python has sorted() and list.sort(). C++ has sort() from <algorithm>. Both sort in-place or return a new list.

Heap/priority queue: Python has heapq. C++ has priority_queue from <queue>. Both support insert and extract-min.

Loop over a range: Python has for i in range(n). C++ has for (int i = 0; i < n; i++). Both iterate n times.

Strings: Python has str with immutable strings. C++ has string with mutable strings. Python's split() is a one-liner; C++ requires a loop or a helper function.

Pairs and tuples: Python has (a, b) tuples. C++ has pair<int, int> from <utility>. Both hold multiple values.

Traps and gotchas

Integer division: Python 3 uses // for integer division and / for float division. C++ uses / for both depending on operand types. 5 / 2 is 2 in C++, not 2.5.

Comparison operators: C++ is stricter about types. You cannot compare an int and a string without explicit conversion. Python does it silently (and often wrongly).

Off-by-one errors: C++ arrays and vectors are 0-indexed, like Python. But many C++ contest solutions use 1-indexed arrays for convenience. Be careful when mixing libraries.

Performance gotchas in C++: using string concatenation in a loop is slow (like Python). Use stringstream to build strings. Passing large vectors by value copies them; pass by reference with const vector<int>& to avoid copies.

Recognising patterns in real code

When you see C++ code in an editorial or on a judge, look for these patterns:

  • while (cin >> x) reads until EOF.
  • vector<vector<int>> is a 2D array (list of lists in Python).
  • map<int, int> cnt; cnt[x]++ is like Python's cnt[x] = cnt.get(x, 0) + 1.
  • sort(v.begin(), v.end()) sorts the vector in-place, like Python's v.sort().

Speed comparison

C++ is faster than Python for the same algorithm because the C++ compiler produces native machine code and does aggressive optimisation. Python runs on an interpreter or JIT compiler. PyPy is much faster than CPython, but C++ is still faster for compute-heavy code.

On a contest, the time limit is set so that a correct algorithm in C++ just barely passes. A correct algorithm in Python usually passes too, because PyPy is fast enough. If your Python solution times out, switch to C++.

Do not switch languages just to be fast. Learning C++ takes time. Coding in C++ is slower than Python. On easy and medium problems, Python is fine. On hard problems where speed is the only barrier, C++ helps.

When to use C++

Use C++ when:

  • Your Python solution is algorithmically correct but times out.
  • The time limit is very tight (under 1 second) and the input is very large (millions of integers).
  • You feel comfortable with C++ syntax and can write it quickly.

Use Python when:

  • Your solution passes in Python.
  • The algorithm is complex and you want to code carefully.
  • You write faster in Python than in C++.

A fast, working solution in Python is better than a buggy attempt at a faster one in C++.

Reading a translated data structure

A binary search you wrote in Python, using a plain list and bisect, translates almost line for line. bisect.bisect_left(arr, x) becomes lower_bound(arr.begin(), arr.end(), x) - arr.begin() in C++: both return the first position where x could be inserted without breaking sorted order. The C++ version returns an iterator, not an index, which is why the code above subtracts arr.begin() to convert it back to a plain integer position, the same kind of value bisect_left hands you directly.

Nested data structures follow the same substitution rules as flat ones. A Python dict mapping a string to a list of integers, dict[str, list[int]], becomes map<string, vector<int>> in C++, and a Python list of dictionaries becomes vector<map<string, int>>. Reading the C++ type from the inside out (a vector of vector<int>s is a list of lists, a map of vectors is a dictionary of lists) is usually enough to see what a piece of unfamiliar C++ is doing, even without knowing every method that type supports.

Recap

C++ shares the same algorithmic ideas as Python. Python lists become vectors, dictionaries become maps, sorting is sorting. The syntax is different, but the logic is the same. Learn to recognise patterns and translate between languages when you need to.