コード例 #1
0
ファイル: LRUCache.cpp プロジェクト: Riddance/LeetCode
    void set(int key, int value) {
        auto got = cache_map.find(key);
        if (got != cache_map.end()) {
            cache_list.erase(got->second);
            cache_map.erase(got);
        }

        cache_list.push_front(make_pair(key, value));
        cache_map.insert(make_pair(key, cache_list.begin()));
        clean();
    }
コード例 #2
0
void update_cache(string url, HTTP_pointer* entity,int status)
{
  if(status == 0)
  {
  	//first check if cache has empty places
  	double MTD=INT_MIN;//minimum access time
  	time_t currentTime = time_current();
  	if(cache.size() < MAX)
  	{
    		//just insert it and return
    		cout<<"Current size of cache: "<<cache.size()<<endl;
    		entity = set_Time(entity);
    		cache.insert(make_pair(url, entity));
    		return;
  	}

  //now if cache is full, find the entry with the oldest access time
  //
  	int i=0;

  	CACHE_LIST::iterator Least_recent_key;
  	CACHE_LIST::iterator N = cache.begin();
  	time_t last;
	for(; N != cache.end(); N++)
  	{
  		HTTP_pointer* en = N->second;
    		last = en->getHeader()->get_last_accessed();
    		double timediff = difftime(currentTime, last);
    		if(timediff > MTD)
    		{
      			MTD = timediff;//find the minima
      			Least_recent_key = N;
    		}
    		i++;
  	}

  //now we have the least recently used key in index leastRecent
  	cout<<"The least recently used(LRU) page is "<<Least_recent_key->first<<", hence this entry will be deleted in the cache"<<endl;
  	cache.erase(Least_recent_key);
  	cache.insert(make_pair(url, entity));
   }
 else
 {

 //method to replace existing entries in cache

  	string key;
	CACHE_LIST::iterator N = cache.begin();

	for(; N != cache.end(); N++)
	{
		key = N->first;
		if(key == url)
		{
			cout<<"Entry found for page "<<key<<", this will be replaced with the new page now"<<endl;
			cache.erase(key);
			entity = set_Time(entity);
			cache.insert(make_pair(url, entity));
			break;
		}
	}
 }
}