回覆編輯1: 我想如果你的數據元素不是很大,比如說只有幾個字節甚至幾十個字節,那麼可以將4096個元素裝入內存。在這種情況下,你需要的是一個哈希表。在C++中,您使用unordered_map
。例如,如果您的密鑰類型爲int
,則可以定義unorderedmap<int, ptr_to_your_node_type>
並獲取O(1)
中的元素。
如果你能很好地設計你的散列並且最壞的情況可能是O(n)
,最快的搜索可能是O(1)
。如果這些項目很大並且無法裝入內存,則可以使用所謂的最近最少使用的緩存algorithm
來節省內存。
用於LRU高速緩存的示例代碼
template <typename K>
class Key_Age{
list<K> key_list;
unordered_map<K, typename list<K> :: iterator> key_pos;
public:
void access(K key){
key_list.erase(key_pos[key]);
insert_new(key);
}
void insert_new(K key){
key_list.push_back(key);
key_pos[key] = --key_list.end();
}
K pop_oldest(){
K t = key_list.front();
key_list.pop_front();
return t;
}
};
class LRU_Cache{
int capacity;
Key_Age<int> key_age;
unordered_map<int, int> lru_cache;
public:
LRU_Cache(int capacity): capacity(capacity) {
}
int get(int key) {
if (lru_cache.find(key) != lru_cache.end()) {
key_age.access(key);
return lru_cache[key];
}
return -1;
}
void set(int key, int value) {
if (lru_cache.count(key) < 1) {
if (lru_cache.size() == capacity) {
int oldest_key = key_age.pop_oldest();
lru_cache.erase(oldest_key);
}
key_age.insert_new(key);
lru_cache[key] = value;
return;
}
key_age.access(key);
lru_cache[key] = value;
}
};
如果您的數組或4096列表是按順序排列的(按字母順序排列或其他)二進制搜索真的很快。 http://en.wikipedia.org/wiki/Binary_search_algorithm – BrettFromLA 2014-09-25 22:32:04