source: trunk/src/lol/core/map.h @ 2108

Last change on this file since 2108 was 2108, checked in by sam, 7 years ago

core: implement a simple linear search map; the API is here, we just
need to make it O(logn) or even O(1) now.

  • Property svn:keywords set to Id
File size: 1.9 KB
Line 
1//
2// Lol Engine
3//
4// Copyright: (c) 2010-2012 Sam Hocevar <sam@hocevar.net>
5//   This program is free software; you can redistribute it and/or
6//   modify it under the terms of the Do What The Fuck You Want To
7//   Public License, Version 2, as published by Sam Hocevar. See
8//   http://sam.zoy.org/projects/COPYING.WTFPL for more details.
9//
10
11//
12// The Map class
13// -------------
14// A very simple Map class.
15//
16
17#if !defined __LOL_CORE_MAP_H__
18#define __LOL_CORE_MAP_H__
19
20namespace lol
21{
22
23/* A stupidly linear map for now */
24template<typename K, typename V> class Map : protected Hash<K>
25{
26public:
27    inline V const& operator[] (K const &key) const
28    {
29        uint32_t hash = ((Hash<K> const &)*this)(key);
30        for (int i = 0; i < m_array.Count(); ++i)
31            if (m_array[i].m1 == hash)
32                if (m_array[i].m2 == key)
33                    return m_array[i].m3;
34        return V();
35    }
36
37    inline V & operator[] (K const &key)
38    {
39        return const_cast<V &>((const_cast<Map<K,V> const &>(*this))[key]);
40    }
41
42    inline V & Set(K const &key, V const &val)
43    {
44        uint32_t hash = ((Hash<K> const &)*this)(key);
45        for (int i = 0; i < m_array.Count(); ++i)
46            if (m_array[i].m1 == hash)
47                if (m_array[i].m2 == key)
48                {
49                    m_array[i].m3.~V();
50                    return m_array[i].m3 = val;
51                }
52
53        m_array.Push(hash, key, val);
54        return m_array.Last().m3;
55    }
56
57    inline void Remove(K const &key)
58    {
59        uint32_t hash = ((Hash<K> const &)*this)(key);
60        for (int i = 0; i < m_array.Count(); ++i)
61            if (m_array[i].m1 == hash)
62                if (m_array[i].m2 == key)
63                {
64                    m_array.Remove(i);
65                    return;
66                }
67    }
68
69private:
70    Array<uint32_t, K, V> m_array;
71};
72
73} /* namespace lol */
74
75#endif // __LOL_CORE_MAP_H__
76
Note: See TracBrowser for help on using the repository browser.