# smallmap_type.hpp

Go to the documentation of this file.

    00001 /* $Id: smallmap_type.hpp 15447 2009-02-11 07:17:39Z peter1138 $ */
    00002
    00005 #ifndef SMALLMAP_TYPE_HPP
    00006 #define SMALLMAP_TYPE_HPP
    00007
    00008 #include "smallvec_type.hpp"
    00009
    00011 template <typename T, typename U>
    00012 struct SmallPair {
    00013   T first;
    00014   U second;
    00015
    00017   FORCEINLINE SmallPair(const T &first, const U &second) : first(first), second(second) { }
    00018 };
    00019
    00024 template <typename T, typename U, uint S = 16>
    00025 struct SmallMap : SmallVector<SmallPair<T, U>, S> {
    00026   typedef ::SmallPair<T, U> Pair;
    00027   typedef Pair *iterator;
    00028
    00030   FORCEINLINE SmallMap() { }
    00032   FORCEINLINE ~SmallMap() { }
    00033
    00038   FORCEINLINE Pair *Find(const T &key)
    00039   {
    00040     for (uint i = 0; i < this->items; i++) {
    00041       if (key == this->data[i].first) return &this->data[i];
    00042     }
    00043     return this->End();
    00044   }
    00045
    00050   FORCEINLINE void Erase(Pair *pair)
    00051   {
    00052     assert(pair >= this->Begin() && pair < this->End());
    00053     *pair = this->data[--this->items];
    00054   }
    00055
    00061   FORCEINLINE bool Erase(const T &key)
    00062   {
    00063     for (uint i = 0; i < this->items; i++) {
    00064       if (key == this->data[i].first) {
    00065         this->data[i] = this->data[--this->items];
    00066         return true;
    00067       }
    00068     }
    00069     return false;
    00070   }
    00071
    00077   FORCEINLINE bool Insert(const T &key, const U &data)
    00078   {
    00079     if (this->Find(key) != this->End()) return false;
    00080     new (this->Append()) Pair(key, data);
    00081     return true;
    00082   }
    00083
    00089   FORCEINLINE U &operator[](const T &key)
    00090   {
    00091     for (uint i = 0; i < this->items; i++) {
    00092       if (key == this->data[i].first) return this->data[i].second;
    00093     }
    00094     Pair *n = this->Append();
    00095     n->first = key;
    00096     return n->second;
    00097   }
    00098
    00099   FORCEINLINE void SortByKey()
    00100   {
    00101     qsort(this->Begin(), this->items, sizeof(Pair), KeySorter);
    00102   }
    00103
    00104   static int CDECL KeySorter(const void *a, const void *b)
    00105   {
    00106     const Pair *pa = (const Pair*)a;
    00107     const Pair *pb = (const Pair*)b;
    00108     return pa->first - pb->first;
    00109   }
    00110 };
    00111
    00112 #endif /* SMALLMAP_TYPE_HPP */