输入一些单词,中间使用空格分隔,最后统计每个单词出现的次数。
#include "stdafx.h"
#include <iostream>
#include <string>
#include <tuple>
#include <iomanip>
#include <array>
#include <map>
#include <functional>
using std::cin;
using std::cout;
using std::endl;
using std::tuple;
using std::string;
using std::setw;
using std::get;
using std::pair;
using std::map;
int main(int argc,_TCHAR* argv[])
{
std::map<string,int> words;
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;
while(begin!=end) //Iterate over words in the stream
words[*begin++]++; //Increment and store a word count
cout<<endl<<"Here a the world counts for the text you entered:"<<endl;
const int wordsPerLine(4);
int wordCount(0);
cout<<std::setiosflags(std::ios::left);
for(auto& word:words)
{
cout<<std::setw(15)<<word.first<<" "<<std::setw(5)<<word.second;
if(++wordCount % wordsPerLine ==0) cout<<endl;
}
cout<<endl;
return 0;
}
运行结果如下: