Fast Input
GOALRead numbers when you are not told how many there are, and make reading fast.
Sometimes a problem says: keep reading numbers until the input runs out. cin >> x reports whether it succeeded, so you can use it as the loop condition. And when there are tens of thousands of numbers, one extra line at the top makes reading several times faster.
ON THIS PAGE
//THE EXAMPLE
#include <iostream>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
vector<int> nums;
int x;
while (cin >> x) {
nums.push_back(x);
}
long long total = 0;
for (int v : nums) {
total = total + v;
}
cout << nums.size() << " " << total << endl;
return 0;
}(input: 10 20 5 15 10) 5 60
//LINE BY LINE
Watch it run
The input is one long stream: 10 20 5 15 10.
The three shapes of input
A problem gives you its input in one of three shapes. The Input Format section tells you which.
// 1. the count comes first
int n; cin >> n;
vector<int> v(n);
for (int i = 0; i < n; i++) cin >> v[i];
// 2. read until the input runs out
int x;
while (cin >> x) v.push_back(x);
// 3. a whole line, spaces and all
string line;
getline(cin, line);The most common mistake: the numbers are on ONE line and you try to read one per line. Python raises ValueError; C++ just gives a wrong answer quietly.
Why sync_with_stdio helps
By default C++ keeps every cin in step with C's own scanf, so that mixing the two still comes out in order. Providing that guarantee is what makes reading slow.
If you never mix them, you do not need the guarantee. Those two lines say "I will only use cin and cout" — and on a hundred thousand numbers the difference is dramatic.
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
// from here on: cin and cout only, never printf or scanf
}After those lines, using printf or scanf scrambles the order of your output. Pick one family and stay in it.