Arithmetic#
+, -, *, / and % work as in C: with two integers, / drops the fraction (7 / 2 is 3) and % is the remainder (7 % 2 is 1). With negatives, % takes the sign of the left side: -7 % 2 is -1.
n % 10 and n / 10 take a number apart one digit at a time, the basis of digit problems.
There is no power operator. pow returns a double, which can be inexact for large results; for whole powers, multiply in a loop.
Shorthand#
i++; // add one
i--; // subtract one
total += x; // total = total + x
total *= 2;
Comparisons and logic#
==, !=, <, >, <=, >= give true or false. Combine with && (and), || (or) and ! (not). Both && and || stop as soon as the answer is known, so put a safety check first:
if (i < (int) v.size() && v[i] == target) { ... }
= assigns, == compares. if (x = 5) is legal and always true; -Wall warns about it.
Reading input with cin#
cin >> reads the next value, skipping spaces and newlines, into a variable of any type:
int a, b;
cin >> a >> b;
cout << a + b << "\n";
string word;
cin >> word; // one word: stops at a space
Reading until input runs out:
long long total = 0;
int x;
while (cin >> x) {
total += x;
}
cin >> x is false once there is nothing left to read, which ends the loop.
Reading a whole line#
string line;
getline(cin, line); // includes spaces
Mixing the two needs care. After cin >> n, the newline you typed is still waiting, and the next getline reads it as an empty line:
int n;
cin >> n;
cin.ignore(); // skip the leftover newline
string line;
getline(cin, line);
Fast input#
For large inputs, these two lines at the start of main make cin and cout much faster:
ios::sync_with_stdio(false);
cin.tie(nullptr);
After this, do not mix cin/cout with scanf/printf in the same program.
Order of operations#
Multiplication, division and remainder before addition and subtraction; arithmetic before comparisons; && before ||. Add brackets whenever a reader might hesitate.
Be careful with << and >> in expressions: they are also shift operators, so cout << a & b does not do what it looks like. Bracket it: cout << (a & b).
Key points#
- Integer
/drops the fraction;%keeps the left side's sign. cin >> xreads one value and is false when input runs out.getlinereads a whole line; usecin.ignore()after>>first.- Two lines at the top of
mainmake large input fast.
Next: strings, which in C++ manage themselves.