Counting list of words in c++ -


now i'm dealing uva problem 10420-list of conquests (link : http://uva.onlinejudge.org/index.php?option=com_onlinejudge&itemid=8&category=24&page=show_problem&problem=1361) . make point i'll make condition on problem simpler . need count how many words inputted. example must input of these.

spain england england france 

and output how many times word inputted. must outputted alphabetically.

england 2 france  1 spain   1 

since don't know words come out how i'll count words condition in c++ ?

in case there used standard container std::map<std::string, size_t>

for example

#include <iostream> #include <string> #include <map>  int main() {    std::map<std::string, size_t> m;    std::string word;     while ( std::cin >> word ) ++m[word];     ( const auto &p : m ) std::cout << p.first << '\t' << p.second << std::endl; } 

you should press either ctrl + z (in windows) or ctrl + d (in unix) finish input of words.

or use function std::getline instead of operator >>

for example

#include <iostream> #include <string> #include <map>  int main() {    std::map<std::string, size_t> m;    std::string word;     while ( std::getline( std::cin, word ) && !word.empty() ) ++m[word];     ( const auto &p : m ) std::cout << p.first << '\t' << p.second << std::endl; } 

in case finish input need enter empty string press enter key.

if input is

spain england england france 

the output be

england 2 france  1 spain   1 

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -