要将此类三角形数组存储在压缩线性向量中,我使用以下类。
#define ogf_array_check(index, data_size) assert(index < data_size)
#define ogf_assert(b) assert(b)
/**
* A 2d array of values aij where only the cells such
* that j <= i are represented.
*/
template <class T> class TriangularArray {
public:
typedef TriangularArray<T> thisclass ;
TriangularArray(int size) : size_(size), data_size_(size * (size + 1) / 2) {
data_ = new T[data_size_] ;
}
~TriangularArray() { delete[] data_; data_ = nil ; }
int size() const { return size_ ; }
int data_size() const { return data_size_ ; }
/**
* index0 denotes the line, and index1 the column,
* note that index1 should be less-than or equal to
* index0.
*/
T& operator()(int index0, int index1) {
ogf_array_check(index0, size_) ;
ogf_array_check(index1, size_) ;
#ifdef OGF_ARRAY_BOUND_CHECK
ogf_assert(index1 <= index0) ;
#endif
int offset = index0 * (index0 + 1) / 2 ;
return data_[offset + index1] ;
}
/**
* index0 denotes the line, and index1 the column,
* note that index1 should be lerr or equal to
* index0.
*/
const T& operator()(int index0, int index1) const {
ogf_array_check(index0, size_) ;
ogf_array_check(index1, size_) ;
#ifdef OGF_ARRAY_BOUND_CHECK
ogf_assert(index1 <= index0) ;
#endif
int offset = index0 * (index0 + 1) / 2 ;
return data_[offset + index1] ;
}
void set_all(const T& value) {
for(int i=0; i<data_size_; i++) {
data_[i] = value ;
}
}
T& from_linear_index(int index) {
ogf_array_check(index, data_size_) ;
return data_[index] ;
}
const T& from_linear_index(int index) const {
ogf_array_check(index, data_size_) ;
return data_[index] ;
}
T* data() const { return data_ ; }
private:
T* data_ ;
int size_ ;
int data_size_ ;
private:
TriangularArray(const thisclass& rhs) ;
thisclass& operator=(const thisclass& rhs) ;
} ;