Programming Traps

partial_sum and overflow in C++

If we have a vector<int> a and vector<int64_t> b, doing partial_sum(a.begin(), a.end(), b.begin()) WILL cause potential overflow, because the implementation is maintaining a running sum of type typename iterator_traits::value_type (int in this case). Similarly, be careful of the initial value in accumulate.

Initialization

I vaguely knew that you can use curly braces when invoking constructors in C++, but never dived into it.

Things like vector<int> a{3, 2}; contradict my intuition. Instead of creating a vector of 3 elements with the value of 2, it creates a vector of 2 elements, with value 3 and 2. That’s called list initialization (see constructor 10 for vector). You can compare https://gcc.godbolt.org/z/j13hfocv8 and https://gcc.godbolt.org/z/1svqMGzcY, and pay attention to the actual constructor invoked. The same applies to string (https://gcc.godbolt.org/z/ed1sjKPMb).

Perhaps the most interesting part is, if a constructor with initializer list is missing, curly braces will match to other constructors.

Tuple Assignment in Python

When you write a, b, c = x, y, z in Python, the assignment happens from left to right.

Most of the time, this won’t be a problem. Until I was dealing with some Linked List problem, and tried to reverse the list as I go. What I wrote was prev, curr, curr.next = curr, curr.next, prev (the curr moves to the next node BEFORE we update curr.next).

endl in C++

From cppreference:

Inserts a newline character into the output sequence os and flushes it as if by calling os.put(os.widen('\n')) followed by os.flush().”

When a problem requires large amounts of output, the repeated flush can lead to slow execution.