Boost の使用を受け入れる場合は、 Boost::Bimapを使用できます。これにより、単語をカウントに関連付け、カウントを単語に (同時に) 関連付けることができます。この例では、テキストの単語数を計算し、ヒストグラムを表示する方法を示します。
ソートされた単語数をときどき表示するだけでよい場合は、通常std::map
の単語数マップを使用する方が高速な場合があります。次に、他の回答に示されている手法を使用して、必要に応じて並べ替えられた単語数を生成します。どちらが速いかを知るには、おそらくベンチマークを実行する必要があります。
完全を期すために、マップのペアをプッシュして、出現順に並べ替えられた単語数を取得することで、ヒープソートを使用する別のソリューションを追加します。std::priority_queue
#include <iostream>
#include <map>
#include <queue>
typedef std::map<std::string, int> MyMap;
struct OrderByOccurence
{
bool operator()(MyMap::const_reference lhs, MyMap::const_reference rhs)
{
// This will make the priority queue sort from highest word count
// to lowest.
return lhs.second < rhs.second;
// This will make the priority queue sort from lowest word count
// to highest.
// return rhs.second < lhs.second;
// Here, you can also check that if both counts are the same,
// the elements should be ordered alphabetically by word.
}
};
int main()
{
MyMap m = {{"a", 1}, {"b", 2}, {"c", 3}};
std::priority_queue<std::pair<std::string, int>,
std::vector< std::pair<std::string, int> >,
OrderByOccurence> q;
for (auto it=m.begin(); it!=m.end(); ++it)
q.push(*it);
while (!q.empty())
{
std::cout << q.top().first << " " << q.top().second << "\n";
q.pop();
}
}