[英]Whats the best c++ stl container for fast lookup?
我搜索具有快速查找時間的容器,並且想要在其中存儲對象,如下所示
class Flow{
const int L3Outside;
const int L4Protocol;
const int L4Oustside;
const int L4Inside;
time_t inOut;
time_t outIn;
}
容器應僅存儲唯一元素,但是為了比較兩個對象是否相等,僅必須比較常量變量。
如果元素未包含在容器中,一半時間我會嘗試插入;如果元素已包含在容器中,一半時間我必須查找並訪問元素。
同樣重要的是,它們不應該是由於哈希引起的任何沖突,或者如果它們是沖突,則我必須能夠插入兩個元素,並且如果它們相等,則僅找到一個元素,不僅它們的哈希值相等。
有什么建議么?
std::multimap
查找:如果該特定鍵有多個元素,則O(log N)
加線性。
插入: O(log N)
看起來是查找和插入的最平衡速度,並且可以很好地處理沖突。
std ::方法是按照上面的答案-將不可變鍵與可變數據分開,這是std::map
或std::unordered_map
。
如果你絕對不能對一些遺留的原因,做到這一點,你可以使用std::set
,並提供自定義的less
仿函數。 或者,您可以使用std::unordered_set
在這種情況下,您需要提供一個自定義的相等函數對象和一個自定義的哈希對象。
但是從c ++ 11開始,請注意std::set<>::iterator
類型具有const語義(即,引用對象不可更改),因此您將需要使用const_cast強制問題:
#include <iostream>
#include <set>
#include <tuple>
#include <utility>
#include <ctime>
struct compare_flow_less;
class Flow{
public:
Flow(int l3o, int l4p, int l4o, int l4i, time_t io = 0, time_t oi = 0)
: L3Outside { l3o }
, L4Protocol { l4p }
, L4Outside { l4o }
, L4Inside { l4i }
, inOut { io }
, outIn { oi }
{
}
void set_times(time_t t1, time_t t2)
{
inOut = t1;
outIn = t2;
}
private:
const int L3Outside;
const int L4Protocol;
const int L4Outside;
const int L4Inside;
time_t inOut;
time_t outIn;
friend compare_flow_less;
};
struct compare_flow_less
{
bool operator()(const Flow&l, const Flow&r)
{
return l.L3Outside < r.L3Outside
&& l.L4Protocol < r.L4Protocol
&& l.L4Outside < r.L4Outside
&& l.L4Inside < r.L4Inside;
}
};
using FlowSet = std::set<Flow, compare_flow_less>;
using namespace std;
int main()
{
FlowSet myflows;
// to insert/overwrite a flow
time_t t1 = time(nullptr);
time_t t2 = t1 + 1;
bool inserted = false;
FlowSet::iterator insert_position;
// try to insert a new one
tie(insert_position, inserted) = myflows.emplace(1,2,3,4,t1,t2);
// if insertion failed, one already exists so update it
if (!inserted) {
const_cast<Flow&>(*insert_position).set_times(t1, t2);
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.