Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. // To compile: gcc --std=gnu++11 freq.cpp -lstdc++ -o freq
  2.  
  3. #include <iostream>
  4. #include <map>
  5. #include <vector>
  6. #include <algorithm>
  7. #include <string>
  8. #include <fstream>
  9. #include <cctype>
  10.  
  11. using namespace std;
  12.  
  13.  
  14. int main(int argc, char *argv[]) {
  15. ifstream in;
  16. ofstream out;
  17.  
  18. if (argc < 3) {
  19. cerr << "too less parametrs \n";
  20. return -1;
  21. }
  22.  
  23. in.open(argv[1]);
  24. if (!in.is_open()) {
  25. cerr << "can't open " << argv[1] << "\n";
  26. }
  27.  
  28. out.open(argv[2]);
  29. if (!out.is_open()) {
  30. cerr << "can't open " << argv[2] << "\n";
  31. }
  32.  
  33. string line;
  34. map<string, int> word_map;
  35. while (getline(in, line)) {
  36. string lc_word;
  37. for(auto ch : line) {
  38. if (isalpha(ch)) {
  39. lc_word += tolower(ch);
  40. continue;
  41. }
  42. if (lc_word.size() > 0) {
  43. word_map[lc_word]++;
  44. lc_word = "";
  45. }
  46. }
  47. if (lc_word.size() > 0) {
  48. word_map[lc_word]++;
  49. lc_word = "";
  50. }
  51. }
  52.  
  53. std::vector<pair<string, int>> out_vector;
  54. for (auto item : word_map) {
  55. out_vector.push_back(item);
  56. }
  57. stable_sort(out_vector.begin(), out_vector.end(), [](const pair<string, int>& a, const pair<string, int>& b)->bool{return a.second > b.second;});
  58.  
  59. for (auto item : out_vector) {
  60. out << item.second << " " << item.first << "\n";
  61. }
  62.  
  63. in.close();
  64. out.close();
  65.  
  66. return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement