例如在 3 維中,我通常會做類似的事情
vector<vector<vector<T>>> v(x, vector<vector<T>>(y, vector<T>(z, val)));
然而,這對于復雜型別和大尺寸來說變得乏味。是否可以定義一種型別,例如tensor,其用法如下:
tensor<T> t(x, y, z, val1);
t[i][j][k] = val2;
uj5u.com熱心網友回復:
模板元編程是可能的。
定義向量 NVector
template<int D, typename T>
struct NVector : public vector<NVector<D - 1, T>> {
template<typename... Args>
NVector(int n = 0, Args... args) : vector<NVector<D - 1, T>>(n, NVector<D - 1, T>(args...)) {
}
};
template<typename T>
struct NVector<1, T> : public vector<T> {
NVector(int n = 0, const T &val = T()) : vector<T>(n, val) {
}
};
你可以像這樣使用它
const int n = 5, m = 5, k = 5;
NVector<3, int> a(n, m, k, 0);
cout << a[0][0][0] << '\n';
我認為很清楚它可以如何使用。還是說吧NVector<# of dimensions, type> a(lengths of each dimension separated by coma (optional)..., default value (optional))。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/392246.html
標籤:C
