Skip to content

Instantly share code, notes, and snippets.

@zeux
Created April 12, 2012 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeux/2365786 to your computer and use it in GitHub Desktop.
Save zeux/2365786 to your computer and use it in GitHub Desktop.
MRU without linked lists and hash maps
#include <cstdio>
#include <cassert>
#include <vector>
#include <string>
class Mru
{
public:
Mru(size_t size): _size(size), _limit(size * size)
{
assert(size > 0);
}
void touch(const std::string& str)
{
_storage.push_back(str);
if (_storage.size() >= _limit) normalize();
}
std::vector<std::string> contents()
{
normalize();
return std::vector<std::string>(_storage.rbegin(), _storage.rend());
}
private:
size_t _size, _limit;
std::vector<std::string> _storage;
void normalize()
{
std::vector<std::string> data(std::move(_storage));
for (std::vector<std::string>::reverse_iterator it = data.rbegin(); it != data.rend(); ++it)
if (_storage.size() < _size && std::find(_storage.begin(), _storage.end(), *it) == _storage.end())
_storage.push_back(*it);
std::reverse(_storage.begin(), _storage.end());
}
};
void DumpMru(Mru& mru, const char* comment)
{
printf("Mru:");
for (auto& s: mru.contents()) printf(" %s", s.c_str());
printf(" -- %s\n", comment);
}
int main()
{
Mru mru(3);
mru.touch("a");
mru.touch("b");
mru.touch("c");
DumpMru(mru, "touch abc");
mru.touch("b");
DumpMru(mru, "touch b");
mru.touch("b");
DumpMru(mru, "retouch b");
mru.touch("d");
DumpMru(mru, "introduce d");
mru.touch("a");
DumpMru(mru, "reintroduce a");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment