00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016 #ifndef OR_TOOLS_UTIL_VECTOR_MAP_H_
00017 #define OR_TOOLS_UTIL_VECTOR_MAP_H_
00018
00019 #include "base/hash.h"
00020 #include <vector>
00021 #include "base/map-util.h"
00022
00023 namespace operations_research {
00024
00025
00026
00027
00028 template <class T> class VectorMap {
00029 public:
00030
00031
00032 int Add(const T& element) {
00033 int current_index = Index(element);
00034 if (current_index != -1) {
00035 return current_index;
00036 }
00037 const int index = list_.size();
00038 CHECK_EQ(index, map_.size());
00039 list_.push_back(element);
00040 map_[element] = index;
00041 return index;
00042 }
00043
00044
00045
00046 void Add(const std::vector<T>& elements) {
00047 for (int i = 0; i < elements.size(); ++i) {
00048 Add(elements[i]);
00049 }
00050 }
00051
00052
00053
00054 int Index(const T& element) const {
00055 return FindWithDefault(map_, element, -1);
00056 }
00057
00058
00059
00060 bool Contains(const T& element) const {
00061 return ContainsKey(map_, element);
00062 }
00063
00064
00065 const T& Element(int index) const {
00066 CHECK_GE(index, 0);
00067 CHECK_LT(index, list_.size());
00068 return list_[index];
00069 }
00070
00071
00072 int size() const { return list_.size(); }
00073
00074
00075 void clear() {
00076 list_.clear();
00077 map_.clear();
00078 }
00079
00080
00081 const std::vector<T>& list() const { return list_; }
00082
00083
00084 typedef T value_type;
00085 typedef const T* pointer;
00086 typedef const T& reference;
00087 typedef const T& const_reference;
00088 typedef size_t size_type;
00089 typedef ptrdiff_t difference_type;
00090 static const size_type npos;
00091 typedef const T* const_iterator;
00092 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
00093 const_iterator begin() const { return list_.data(); }
00094 const_iterator end() const { return list_.data() + list_.size(); }
00095 const_reverse_iterator rbegin() const {
00096 return const_reverse_iterator(list_.data() + list_.size());
00097 }
00098 const_reverse_iterator rend() const {
00099 return const_reverse_iterator(list_.data());
00100 }
00101
00102 private:
00103 std::vector<T> list_;
00104 hash_map<T, int> map_;
00105 };
00106
00107 }
00108 #endif // OR_TOOLS_UTIL_VECTOR_MAP_H_