МК
Size: a a a
МК
А
МК
МП
А
AS
#include <QDebug>
#include <QList>
#include <QString>
#include <map>
#include <span>
#include <vector>
class Histogram {
using CounterMap = std::map<QString, int>;
CounterMap m_counter;
mutable bool m_invalidated = false;
mutable std::vector<CounterMap::const_iterator> m_order;
public:
void append(QString key)
{
m_counter[std::move(key)]++;
m_invalidated = true;
}
std::span<CounterMap::const_iterator> top(size_t n = 0) const
{
if (m_invalidated) {
reorder();
}
if (!n) {
n = m_counter.size();
}
return std::span(m_order.begin(), n);
}
private:
void reorder() const
{
m_order.clear();
m_order.reserve(m_counter.size());
for (auto&& it = m_counter.begin(); it != m_counter.end(); ++it) {
m_order.emplace_back(it);
}
std::sort(m_order.begin(), m_order.end(), [](auto&& a, auto&& b) {
return b->second < a->second;
});
m_invalidated = false;
}
};
int main(int, char*[])
{
Histogram historam;
QList<QString> keys { "one", "two", "three", "one", "three", "one" };
for (auto&& key : keys) {
historam.append(key);
}
auto&& top = historam.top();
for (auto&& e : top) {
qDebug() << e->first << e->second;
}
}
AS
AS
#
#
AS
#
AS
AS
#