字符串重复数量统计排序

统计并排序

数据:向map插入数据时候自增统计,完成对word数量的统计

  • sortPair原理
    把map中的所有pair元素插入 vector,然后使用 sort,完成排序,效率低

  • queueSortPair
    把map的元素插入数量有限的小端优先队列,比队列的最小值小的时候可以插入,
    从而保存最大的几个值。

#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
//#include <set>
#include <functional>
#include <queue>
#include <vector>

using namespace std;
typedef pair<string, int> PAIR;
// bool cmp(const PAIR &a, const PAIR &b) { return a.second > b.second; }
struct cmp {
  bool operator()(const PAIR &a, const PAIR &b) const {
    return a.second > b.second;
  }
};

void sortPair(map<string, int> mymap) {
  vector<PAIR> vectPair(mymap.begin(), mymap.end());
  std::sort(
      vectPair.begin(), vectPair.end(),
      [](const PAIR &lhs, const PAIR &rhs) { return lhs.second > rhs.second; });

  for (auto &it : vectPair) {
    cout << it.first << ":" << it.second << endl;
  }
}
void queueSortPair(map<string, int> vectPair) {
  priority_queue<PAIR, vector<PAIR>, cmp> priQueue;
  map<string, int>::iterator it;
  int i = 0;
  for (it = vectPair.begin(); it != vectPair.end(); it++, i++) {
    if (i < 3) {
      priQueue.push(*it);
    } else {
      if (it->second > priQueue.top().second) {
        priQueue.pop();
        priQueue.push(*it);
      }
    }
  }

  while (!priQueue.empty()) {
    cout << priQueue.top().first << ":" << priQueue.top().second << endl;
    priQueue.pop();
  }
}

int main() {
  fstream ifs("test.txt");
  if (!ifs) {
    return 1;
  }
  string word;
  std::map<string, int> mymap;
  // std::multiset<string> myset;
  while (ifs >> word) {
    // myset.insert(word);
    // mymap[word] = myset.count(word);
    mymap[word] += 1;
  }
  queueSortPair(mymap);
  cout << "-------------" << endl;
  sortPair(mymap);

  return 0;
}
原文地址:https://www.cnblogs.com/ims-/p/13865896.html