C++ Notes

I got to know something about C++ when learning CS106X-Stanford and Object-Oriented Programming-Zhejiang University . However, I haven’t studied C++ specially. In this summer vacation, I will dig into C++ and keep some notes here.

The data structure part has been moved to the new post Data Structures and Algorithms Cheatsheet (C++). The remaining part of this post is mainly about language features.

Adding Literals and strings

For historical reasons, and for compatibility with C, string literals are not standard library strings. It is important to remember that these types differ when you use string literals and library strings.

When we mix strings and string or character literals, at least one operand to each + operator must be of string type. Thus, it is illegal to add two string literals. (error: invalid operands to binary expression ('const char *' and 'const char *'))

Unsigned ints

Be careful when using loops like

for (int i = 0; i < v.size() - 1; i++) //...

Because .size() returns the type size_type instead of int. It is an unsigned integral type and when v is empty, v.size() - 1 would become the maximum integer rather than -1.

Generic Programming

Use != rather than < in for loops.

Use iterators rather than subscripts.