MultiIndex
multitable.hpp
Go to the documentation of this file.
00001 
00002 // Copyright 2012 Yandex Artem Babenko
00003 #pragma once
00004 
00005 #include <vector>
00006 
00007 using std::vector;
00008 
00014 template<class T>
00015 struct Multitable {
00020   Multitable(const vector<int>& dimensions = vector<int>());
00025   void Resize(const vector<int>& dimensions, T value = T());
00031   void SetValue(T value, const vector<int>& cell_indices);
00036   T GetValue(const vector<int>& cell_indices);
00040   vector<T> table;
00044   vector<int> dimensions;
00048   template<class Archive>
00049   void serialize(Archive& arc, unsigned int version) {
00050     arc & table;
00051     arc & dimensions;
00052   }
00057   int GetCellGlobalIndex(const vector<int>& cell_indices) const;
00058 };
00059 
00060 template<class T>
00061 int Multitable<T>::GetCellGlobalIndex(const vector<int>& indices) const {
00062   if(indices.empty()) {
00063     throw std::logic_error("Empty indices array!");
00064   }
00065   int global_index = 0;
00066   int subtable_capacity = table.size();
00067   for(int dimension_index = 0; dimension_index < dimensions.size(); ++dimension_index) {
00068     subtable_capacity = subtable_capacity / dimensions[dimension_index];
00069     global_index += subtable_capacity * indices[dimension_index];
00070   }
00071   return global_index;
00072 }
00073 
00074 template<class T>
00075 void Multitable<T>::Resize(const vector<int>& new_dimensions, T value) {
00076   int table_size = 1;
00077   dimensions = new_dimensions;
00078   for(int dimension_index = 0; dimension_index < new_dimensions.size(); ++dimension_index) {
00079     table_size *= new_dimensions[dimension_index];
00080   }
00081   table.resize(table_size, value);
00082 }
00083 
00084 template<class T>
00085 Multitable<T>::Multitable(const vector<int>& dimensions) {
00086   Resize(dimensions);
00087 }
00088 
00089 template<class T>
00090 void Multitable<T>::SetValue(T value, const vector<int>& indices) {
00091   int global_index = GetCellGlobalIndex(indices);
00092   table.at(global_index) = value;
00093 }
00094 
00095 template<class T>
00096 T Multitable<T>::GetValue(const vector<int>& indices) {
00097   int global_index = GetCellGlobalIndex(indices);
00098   return table.at(global_index);
00099 }
 All Classes Files Functions Variables Typedefs Enumerations Enumerator