I’ve got this short snippet of code. I don’t understand what this construction means. I know this snippet of code reads numbers from input and counts its frequency in an unordered_map. But what is [&]? And what is the meaning of (int x)? What does the input(cin) stand for? I mean the “cin” in parentheses? And how can for_each iterate from input(cin) to empty eof parameter? I don’t understand of this whole construction.
unordered_map<int,int> frequency;
istream_iterator<int> input(cin);
istream_iterator<int> eof;
for_each(input, eof, [&] (int x)
{ frequency[x]++; });
istream_iteratorallows you to iteratively extract items from anistream, which you pass in to the constructor. Theeofobject is explained thus:for_eachis a loop construct that takes iterator #1 and increments it until it becomes equal with iterator #2. Here it takes the iterator that wraps standard inputcinand increments it (which translates to extracting items) until there is no more input to consume — this makesinputcompare equal toeofand the loop ends.The construct
[&] (int x) { frequency[x]++; }is an anonymous function; it is simply a shorthand way to write functions inline. Approximately the same effect could be achieved withSo in a nutshell: this code reads integers from standard input until all available data is consumed, keeping a count of each integer’s appearance frequency in a map.