00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012 #ifndef SPARSE_ARRAY_H
00013 #define SPARSE_ARRAY_H
00014
00015 template <typename I, typename T> class sparse_array {
00016 public:
00017 typedef std::map<I, T> container_type;
00018 typedef typename container_type::size_type size_type;
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028 T operator[](size_type index) const {
00029 typename container_type::const_iterator it = container.find(index);
00030 if (it != container.end())
00031 return it->second;
00032 else
00033 return 0;
00034 }
00035
00036
00037
00038
00039
00040
00041 T & operator[](size_type index) {
00042 return container[index];
00043 }
00044
00045
00046
00047
00048
00049 sparse_array & operator+=(sparse_array const & rhs) {
00050 typename container_type::const_iterator it = rhs.container.begin();
00051 typename container_type::const_iterator it_end = rhs.container.end();
00052 for ( ; it != it_end; it++)
00053 container[it->first] += it->second;
00054
00055 return *this;
00056 }
00057
00058
00059
00060
00061
00062
00063 sparse_array & operator-=(sparse_array const & rhs) {
00064 typename container_type::const_iterator it = rhs.container.begin();
00065 typename container_type::const_iterator it_end = rhs.container.end();
00066 for ( ; it != it_end; it++)
00067 container[it->first] -= it->second;
00068
00069 return *this;
00070 }
00071
00072
00073
00074
00075
00076
00077 size_type size() const {
00078 if (container.size() == 0)
00079 return 0;
00080 typename container_type::const_iterator last = container.end();
00081 --last;
00082 return last->first + 1;
00083 }
00084
00085
00086
00087 bool zero() const {
00088 typename container_type::const_iterator it = container.begin();
00089 typename container_type::const_iterator it_end = container.end();
00090 for ( ; it != it_end; it++)
00091 if (it->second != 0)
00092 return false;
00093 return true;
00094 }
00095
00096 private:
00097 container_type container;
00098 };
00099
00100 #endif // SPARSE_ARRAY_H