114 lines
3.0 KiB
C++
114 lines
3.0 KiB
C++
#ifndef A8_COMMONRANK_H
|
|
#define A8_COMONRANK_H
|
|
|
|
#include <algorithm>
|
|
|
|
namespace a8
|
|
{
|
|
|
|
template <class T>
|
|
class CommonRank
|
|
{
|
|
private:
|
|
std::vector<T*> list_;
|
|
std::set<T*> set_;
|
|
std::function<bool (const T*, const T*)> cmp_func_;
|
|
size_t max_num_ = 0;
|
|
|
|
public:
|
|
|
|
CommonRank() {}
|
|
CommonRank(std::function<bool (const T*, const T*)> cmp_func, size_t max_num)
|
|
{
|
|
cmp_func_ = cmp_func;
|
|
max_num_ = max_num;
|
|
}
|
|
|
|
size_t Size()
|
|
{
|
|
return list_.size();
|
|
}
|
|
|
|
const std::vector<T*>& GetList()
|
|
{
|
|
return list_;
|
|
}
|
|
|
|
void Sort()
|
|
{
|
|
std::sort(list_.begin(), list_.end(), cmp_func_);
|
|
}
|
|
|
|
void Update(T* val)
|
|
{
|
|
if (Size() < max_num_) {
|
|
if (!Exists(val)) {
|
|
list_.push_back(val);
|
|
set_.insert(val);
|
|
Sort();
|
|
}
|
|
} else {
|
|
if (cmp_func_(val, list_[list_.size() - 1])) {
|
|
if (!Exists(val)) {
|
|
set_.erase(list_[list_.size() - 1]);
|
|
list_[list_.size() - 1] = val;
|
|
set_.insert(val);
|
|
Sort();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
bool Exists(T* val)
|
|
{
|
|
return set_.find(val) != set_.end();
|
|
}
|
|
|
|
void Remove(T* val)
|
|
{
|
|
if (!Exists(val)) {
|
|
return;
|
|
}
|
|
{
|
|
auto itr = std::find(list_.begin(), list_.end(), val);
|
|
if (itr != list_.end()) {
|
|
list_.erase(itr);
|
|
}
|
|
}
|
|
set_.erase(val);
|
|
}
|
|
|
|
};
|
|
|
|
template <typename T>
|
|
a8::CommonRank<T>& ForceCreateCommonRankList(std::map<long long, a8::CommonRank<T>>& rank_list,
|
|
long long key,
|
|
std::function<bool (const T*, const T*)> cmp_func,
|
|
size_t max_num)
|
|
{
|
|
auto itr = rank_list.find(key);
|
|
if (itr != rank_list.end()) {
|
|
return itr->second;
|
|
}
|
|
rank_list[key] = a8::CommonRank<T>(cmp_func, max_num);
|
|
return rank_list[key];
|
|
}
|
|
|
|
template <typename T>
|
|
static a8::CommonRank<T>& ForceCreateCommonRankList(std::map<std::string, a8::CommonRank<T>>& rank_list,
|
|
const std::string& key,
|
|
std::function<bool (const T*, const T*)> cmp_func,
|
|
size_t max_num)
|
|
{
|
|
auto itr = rank_list.find(key);
|
|
if (itr != rank_list.end()) {
|
|
return itr->second;
|
|
}
|
|
rank_list[key] = a8::CommonRank<T>(cmp_func, max_num);
|
|
return rank_list[key];
|
|
}
|
|
|
|
}
|
|
|
|
#endif
|