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
00032 template <typename T, typename U, uint S = 16>
00033 struct SmallMap : SmallVector<SmallPair<T, U>, S> {
00034 typedef ::SmallPair<T, U> Pair;
00035 typedef Pair *iterator;
00036 typedef const Pair *const_iterator;
00037
00039 FORCEINLINE SmallMap() { }
00041 FORCEINLINE ~SmallMap() { }
00042
00047 FORCEINLINE Pair *Find(const T &key)
00048 {
00049 for (uint i = 0; i < this->items; i++) {
00050 if (key == this->data[i].first) return &this->data[i];
00051 }
00052 return this->End();
00053 }
00054
00059 FORCEINLINE void Erase(Pair *pair)
00060 {
00061 assert(pair >= this->Begin() && pair < this->End());
00062 *pair = this->data[--this->items];
00063 }
00064
00070 FORCEINLINE bool Erase(const T &key)
00071 {
00072 for (uint i = 0; i < this->items; i++) {
00073 if (key == this->data[i].first) {
00074 this->data[i] = this->data[--this->items];
00075 return true;
00076 }
00077 }
00078 return false;
00079 }
00080
00086 FORCEINLINE bool Insert(const T &key, const U &data)
00087 {
00088 if (this->Find(key) != this->End()) return false;
00089 new (this->Append()) Pair(key, data);
00090 return true;
00091 }
00092
00098 FORCEINLINE U &operator[](const T &key)
00099 {
00100 for (uint i = 0; i < this->items; i++) {
00101 if (key == this->data[i].first) return this->data[i].second;
00102 }
00103 Pair *n = this->Append();
00104 n->first = key;
00105 return n->second;
00106 }
00107
00108 FORCEINLINE void SortByKey()
00109 {
00110 QSortT(this->Begin(), this->items, KeySorter);
00111 }
00112
00113 static int CDECL KeySorter(const Pair *a, const Pair *b)
00114 {
00115 return a->first - b->first;
00116 }
00117 };
00118
00119 #endif