Re: counting input words
arnuld wrote:
any comments for improvement:
/* C++ Primer - 4/e
*
* CHAPTER 10 - Associative Containers
*
* EXERCISE - 10.7
* Write a program to count and print the number of times each word
* occured in the input.
Well, the obvious question is: how do you define a word? I'd
say that this should be documented. (For purposes of learning,
what you've done is actually quite good. But it certainly
doesn't define word in the usual English language sense.)
*
*/
#include <iostream>
#include <string>
#include <vector>
#include <map>
int main()
{
std::map<std::string, int> word_count;
std::string aword;
while( std::cin >> aword )
{
++word_count[aword];
}
The one thing I'd do differently (but again, it's probably not
necessary in an exercise): I'd use a class instead of int as the
counter. A class which checked for overflow, and gave defined
behavior in that case.
I might also use a class Word, to facilitate changing its
definition (although it would start as a trivial wrapper for
std::string).
Both of these concepts are related to more industrial
considerations, though, and aren't necessarily relevant in a
learning context.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34