Created
February 5, 2017 13:26
-
-
Save macrat/459aba0038887e933e12eb4ff06e7525 to your computer and use it in GitHub Desktop.
C#でLRUキャッシュ的なもの
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
using System; | |
class LRUCache<K, V> | |
where K : IComparable | |
{ | |
private int Size; | |
private List<KeyValuePair<K, V>> Values; | |
public LRUCache(int size) { | |
Size = size; | |
Values = new List<KeyValuePair<K, V>>(); | |
} | |
private KeyValuePair<K, V> GetRaw(K key) { | |
try { | |
return Values.First(y => y.Key.Equals(key)); | |
} catch (InvalidOperationException) { | |
throw new KeyNotFoundException(); | |
} | |
} | |
public V Get(K key) { | |
KeyValuePair<K, V> x; | |
x = GetRaw(key); | |
Values.Remove(x); | |
Values.Add(x); | |
return x.Value; | |
} | |
public void Set(K key, V val) { | |
KeyValuePair<K, V> x; | |
try { | |
x = GetRaw(key); | |
Values.Remove(x); | |
} catch (KeyNotFoundException) { | |
x = new KeyValuePair<K, V>(key, val); | |
} | |
Values.Add(x); | |
if (Values.Count > Size) { | |
Values.Remove(Values[0]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment