Hello everyone,
I have a small question about the code below, I understand just about every part of it.
Except for this small snippet, could someone explain how the loop works?
while(begin != end ) //<-- I believe the stream iterator is getting input here
words[*begin++]++; // <-- I can see here that the string that was typed in is stored in the map words(*begin), but how is the int in the map being accessed and incremented and when the words are outputted how have they been separated? When I dereference *begin I get the whole string that was typed, but when I output them at the end of the program they have been seperated.
// A simple word counting program
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <iterator>
using std::cout;
using std::cin;
using std::endl;
using std::string;
int main()
{
std::map<string, int> words; // Map to store words and word counts
cout << "Enter some text and press Enter followed by Ctrl+Z then Enter to end:"
<< endl << endl;
std::istream_iterator<string> begin(cin); // Stream iterator
std::istream_iterator<string> end; // End stream iterator
while(begin != end ) // Iterate over words in the stream
words[*begin++]++; // Increment and store a word count
// Output the words and their counts
cout << endl << "Here are the word counts for the text you entered:" << endl;
for(auto iter = words.begin() ; iter != words.end() ; ++iter)
cout << std::setw(5) << iter->second << " " << iter->first << endl;
return 0;
}