3

如何2D vector在 C++ 中创建 a 并找到它的lengthand coordinates

在这种情况下,向量元素如何填充值?

谢谢。

4

3 回答 3

5

如果您的目标是进行矩阵计算,请使用Boost::uBLAS。这个库有许多线性代数函数,可能比你手工构建的任何东西都要快得多。

如果您是受虐狂并想坚持使用std::vector,则需要执行以下操作:

std::vector<std::vector<double> > matrix;
matrix.resize(10);
matrix[0].resize(20);
// etc
于 2011-01-30T19:07:41.907 回答
3

你有很多选择。最简单的是原始二维数组:

int *mat = new int[width * height];

要使用特定值填充它,您可以使用std::fill()

std::fill(mat, mat + width * height, 42);

要使用任意值填充它,请使用std::generate()or 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

于 2011-01-30T19:18:51.273 回答
1

(S)他想要向量,就像物理学中一样。

要么自己动手做练习:

class Vector2d
{
  public:
    // basic math (length: pythagorean theorem, coordinates: you are storing those)
  private: float x,y;
};

或使用定义了 Vector2f 的库,如 Eigen

于 2014-11-06T20:36:16.427 回答