我正在嘗試撰寫一個簡單的 C 頭檔案庫,它實作了一些基本的數值演算法。這是一個業余專案,我希望在我的個人時間做。
我創建了一個MatrixX表示動態大小矩陣的 C 類,即它的維度可以在運行時提供。說,我們創建一個MatrixX物件如下:
MatrixXd m {
{1, 0, 0},
{0, 1, 0},
{0, 0, 1}
};
我的MatrixX<scalarType>模板化類std::vector<scalarType>用作存盤資料的容器。
目前,如果我寫m.row(i),它回傳矩陣的第 i 行向量。我還想要的是,能夠m.row(i)在賦值陳述句的左側。就像是:
m.row(i) = {{1, 2, 3}};
m.row(j) = m.row(j) - 2*m.row(i);
有沒有人有任何關于如何在 C 中完成這項任務的提示/技巧?我將我的源代碼、單元測驗和檔案包含在下面的鏈接中,為簡潔起見,我沒有將其行內粘貼。
- 檔案
- 源代碼
- 單元測驗
uj5u.com熱心網友回復:
這種情況的一種常見方法是讓該row()方法回傳一個代表行而不是行本身的代理物件。
然后,您可以RowProxy通過讓其操作檢查和操縱創建它的矩陣來自由地實作它的行為方式。
這是一個粗略的起點:
template<typename T>
class RowProxy {
public:
template<std::size_t N>
RowProxy& operator=(const std::array<T, N>& rhs) {
assert(N == row_index_.columns());
// ...
}
RowProxy& operator=(const RowProxy& rhs) {
assert(matrix_.columns() == rhs.matrix_.columns());
// ...
}
RowProxy& operator=(const Vector<T>& rhs) {
assert(matrix_.columns() == rhs.matrix_.columns());
// ...
}
Vector<T>& operator*(const T& scalar) const {
return ...;
}
// more operators...
private:
MatrixX<T>& matrix_;
std::size_t row_;
template<typename T>
friend class MatrixX;
RowProxy(MatrixX<T>& m, std::size_t r) : matrix_(m), row_(r) {}
};
template<typename T>
struct MatrixX {
public:
// ...
RowProxy<T> row(std::size_t index) {
return RowProxy<T>{*this, index};
}
// ...
};
template<typename T>
Vector<T>& operator*(const T& scalar, const RowProxy* rhs) const {
return rhs * scalar;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/362852.html
