smallmap_type.hpp
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00012 #ifndef SMALLMAP_TYPE_HPP
00013 #define SMALLMAP_TYPE_HPP
00014
00015 #include "smallvec_type.hpp"
00016 #include "sort_func.hpp"
00017
00019 template <typename T, typename U>
00020 struct SmallPair {
00021 T first;
00022 U second;
00023
00025 FORCEINLINE SmallPair(const T &first, const U &second) : first(first), second(second) { }
00026 };
00027
00033 template <typename T, typename U, uint S = 16>
00034 struct SmallMap : SmallVector<SmallPair<T, U>, S> {
00035 typedef ::SmallPair<T, U> Pair;
00036 typedef Pair *iterator;
00037 typedef const Pair *const_iterator;
00038
00040 FORCEINLINE SmallMap() { }
00042 FORCEINLINE ~SmallMap() { }
00043
00049 FORCEINLINE Pair *Find(const T &key)
00050 {
00051 for (uint i = 0; i < this->items; i++) {
00052 if (key == this->data[i].first) return &this->data[i];
00053 }
00054 return this->End();
00055 }
00056
00062 FORCEINLINE bool Contains(const T &key)
00063 {
00064 return this->Find(key) != this->End();
00065 }
00066
00072 FORCEINLINE void Erase(Pair *pair)
00073 {
00074 assert(pair >= this->Begin() && pair < this->End());
00075 *pair = this->data[--this->items];
00076 }
00077
00084 FORCEINLINE bool Erase(const T &key)
00085 {
00086 for (uint i = 0; i < this->items; i++) {
00087 if (key == this->data[i].first) {
00088 this->data[i] = this->data[--this->items];
00089 return true;
00090 }
00091 }
00092 return false;
00093 }
00094
00101 FORCEINLINE bool Insert(const T &key, const U &data)
00102 {
00103 if (this->Contains(key)) return false;
00104 Pair *n = this->Append();
00105 n->first = key;
00106 n->second = data;
00107 return true;
00108 }
00109
00116 FORCEINLINE U &operator[](const T &key)
00117 {
00118 for (uint i = 0; i < this->items; i++) {
00119 if (key == this->data[i].first) return this->data[i].second;
00120 }
00121 Pair *n = this->Append();
00122 n->first = key;
00123 return n->second;
00124 }
00125
00126 FORCEINLINE void SortByKey()
00127 {
00128 QSortT(this->Begin(), this->items, KeySorter);
00129 }
00130
00131 static int CDECL KeySorter(const Pair *a, const Pair *b)
00132 {
00133 return a->first - b->first;
00134 }
00135 };
00136
00137 #endif