[英]C++ 2D vector and operations
如何在C ++中創建2D vector
並找到它的length
和coordinates
?
在這種情況下,向量元素如何填充值?
謝謝。
如果您的目標是進行矩陣計算,請使用Boost :: uBLAS 。 該庫具有許多線性代數函數,並且可能比您手動構建的任何函數快得多。
如果你是一個受虐狂,並想堅持使用std::vector
,你需要做類似以下的事情:
std::vector<std::vector<double> > matrix;
matrix.resize(10);
matrix[0].resize(20);
// etc
你有很多選擇。 最簡單的是原始的二維數組:
int *mat = new int[width * height];
要使用特定值填充它,您可以使用std::fill()
:
std::fill(mat, mat + width * height, 42);
要使用任意值填充它,請使用std::generate()
或std::generate_n()
:
int fn() { return std::rand(); }
// ...
std::generate(mat, mat + width * height, fn);
完成使用后,您必須記住delete
數組:
delete[] mat;
因此,將數組包裝在類中是個好主意,因此您不必記住每次創建時都刪除它:
struct matrix {
matrix(int w, int h);
matrix(const matrix& m);
matrix& operator=(const matrix& m);
void swap(const matrix& m);
~matrix();
};
// ...
matrix mat(width, height);
但當然,有人已經為你完成了這項工作。 看一下boost::multi_array
。
(S)他想要物理學中的矢量。
或者將自己作為練習:
class Vector2d
{
public:
// basic math (length: pythagorean theorem, coordinates: you are storing those)
private: float x,y;
};
或使用像Eigen這樣定義了Vector2f的庫
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.