Ignore:
Timestamp:
Nov 22, 2012, 2:05:40 PM (8 years ago)
Author:
sam
Message:

core: we can now set Map elements using simply map[foo] = bar, no need for
a Set() method. Also, new HasKey() method.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/lol/core/map.h

    r2108 r2109  
    2121{
    2222
    23 /* A stupidly linear map for now */
     23/* A stupidly linear map for now. */
    2424template<typename K, typename V> class Map : protected Hash<K>
    2525{
    2626public:
     27    /* I choose to make this inline because passing the key by reference
     28     * is usually suboptimal. */
    2729    inline V const& operator[] (K const &key) const
    2830    {
     31        /* Look for the hash in our table and return the value. */
    2932        uint32_t hash = ((Hash<K> const &)*this)(key);
    3033        for (int i = 0; i < m_array.Count(); ++i)
     
    3235                if (m_array[i].m2 == key)
    3336                    return m_array[i].m3;
     37        /* XXX: this in an error! */
    3438        return V();
    3539    }
     
    3741    inline V & operator[] (K const &key)
    3842    {
    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     {
     43        /* Look for the hash in our table and return the value if found. */
    4444        uint32_t hash = ((Hash<K> const &)*this)(key);
    4545        for (int i = 0; i < m_array.Count(); ++i)
    4646            if (m_array[i].m1 == hash)
    4747                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);
     48                    return m_array[i].m3;
     49        /* If not found, insert a new value. */
     50        m_array.Push(hash, key, V());
    5451        return m_array.Last().m3;
    5552    }
     
    6764    }
    6865
     66    inline bool HasKey(K const &key)
     67    {
     68        uint32_t hash = ((Hash<K> const &)*this)(key);
     69        for (int i = 0; i < m_array.Count(); ++i)
     70            if (m_array[i].m1 == hash)
     71                if (m_array[i].m2 == key)
     72                    return true;
     73        return false;
     74    }
     75
    6976private:
    7077    Array<uint32_t, K, V> m_array;
Note: See TracChangeset for help on using the changeset viewer.