![](/img/trans.png)
[英]C++ vector of priority_queue of strings with custom strings comparator
[英]Vector of maps with custom comparator
我正在嘗試創建map
的vector
。 每個map
都有一個不同的比較器。
這是我嘗試過的: -
#include<iostream>
#include<map>
#include<vector>
template <class T>
struct head {
virtual bool operator() (const T& x, const T& y) const = 0;
};
template <class T>
struct greater: head<T> {
bool operator() (const T& x, const T& y) const {return x>y;}
};
template <class T>
struct less: head<T> {
bool operator() (const T& x, const T& y) const {return x<y;}
};
int main()
{
std::vector<std::map<int, int, head<int>>> mp;
return 0;
}
但是我收到一個錯誤,即my operator()
在head中是純虛擬的。
請告訴我實現這一目標的正確方法是什么?
您需要一個適用於所有向量的比較器類型。 像這樣:
template<typename T>
struct comp {
comp(bool gt) : do_greater(gt) {}
bool operator() (const T& x, const T& y) const
{
return do_greater ? x > y : x < y;
}
bool do_greater;
};
int main()
{
std::vector<std::map<int, int, comp<int>>> mp;
mp.emplace_back(false); // first map uses less-than
mp.emplace_back(true); // first map uses greater-than
}
即比較function的選擇需要由每個std::map構造函數中初始化的state驅動。 那個單一的?:
分支在性能方面可能也比每次都調用一個虛擬方法更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.