关于使用Stroustrup的matrix.h实现动态矩阵分配与填充的技术求助
matrix.h Without Manual Memory Management (Plus Boost uBLAS Considerations) Hey there, let's break down your problem step by step so you can get this matrix populated cleanly without messy manual memory handling.
First: You Don't Need new for This
Let's clear up the biggest misconception first—you absolutely don't need to use new here. Stroustrup's matrix template stores its elements as value types (in your case, doubles), not pointers. That means when you assign inputLayer[i][j] = asNumber(...), you're directly writing a double value into the matrix's preallocated storage, no dynamic memory management required. The matrix will automatically clean up its memory when it goes out of scope, just like a std::vector.
Fix the Matrix Initialization
Your current code has a critical gap: you're declaring Matrix<double,2> inputLayer; but not initializing it with the correct row and column count you get at runtime. Without this, the matrix will have a default size (probably 0x0 or some small default), and writing to inputLayer[i][j] will cause undefined behavior.
Instead, initialize the matrix with the runtime-derived dimensions first:
// Get runtime dimensions int numRows = sourceSeries->rowCount(); int numColumns = sourceSeries->columnCount(); // Initialize matrix with the correct size first Matrix<double,2> inputLayer(numRows, numColumns); // Now populate it for(int i = 0; i < numRows; ++i) { for(int j = 0; j < numColumns; ++j) { // Skip header row by using i+1 for the source index inputLayer[i][j] = asNumber(sourceSeries->data(i+1, j, ItemDataRole::Display)); } }
This way, the matrix allocates exactly the right amount of storage upfront, and you can safely write to each element without issues.
Should You Switch to Boost uBLAS?
Now, about your Boost uBLAS dilemma: it depends on your long-term needs:
- Stick with Stroustrup's
matrix.hif: You only need basic dense matrix storage and simple computations, and you want a lightweight, minimal dependency solution. Once you fix the initialization step, it'll work exactly as you want, with automatic memory management. - Switch to Boost uBLAS if: You anticipate needing more advanced linear algebra operations later (matrix multiplication, inversion, slicing, iterators, etc.). uBLAS has a much richer API, better integration with other Boost libraries, and is widely used in production code for numerical tasks. It also supports dynamic-sized matrices seamlessly, so populating it would be similar to the code above—initialize with runtime dimensions, then loop to assign values.
Quick Code Check
One tiny thing to note in your original code: int i,j = 0; only initializes j to 0, i is left uninitialized. Always initialize loop variables explicitly like in the corrected code above to avoid bugs.
内容的提问来源于stack exchange,提问作者Mark Travis

