简体   繁体   English

C ++ 2D矢量和操作

[英]C++ 2D vector and operations

How can one create a 2D vector in C++ and find its length and coordinates ? 如何在C ++中创建2D vector并找到它的lengthcoordinates

In this case, how are the vector elements filled with values? 在这种情况下,向量元素如何填充值?

Thanks. 谢谢。

If your goal is to do matrix computations, use Boost::uBLAS . 如果您的目标是进行矩阵计算,请使用Boost :: uBLAS This library has many linear algebra functions and will probably be a lot faster than anything you build by hand. 该库具有许多线性代数函数,并且可能比您手动构建的任何函数快得多。

If you are a masochist and want to stick with std::vector , you'll need to do something like the following: 如果你是一个受虐狂,并想坚持使用std::vector ,你需要做类似以下的事情:

std::vector<std::vector<double> > matrix;
matrix.resize(10);
matrix[0].resize(20);
// etc

You have a number of options. 你有很多选择。 The simplest is a primitive 2-dimensional array: 最简单的是原始的二维数组:

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

To fill it with a specific value you can use std::fill() : 要使用特定值填充它,您可以使用std::fill()

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

To fill it with arbitrary values use std::generate() or std::generate_n() : 要使用任意值填充它,请使用std::generate()std::generate_n()

int fn() { return std::rand(); }

// ...
std::generate(mat, mat + width * height, fn);

You will have to remember to delete the array when you're done using it: 完成使用后,您必须记住delete数组:

delete[] mat;

So it's a good idea to wrap the array in a class, so you don't have to remember to delete it every time you create it: 因此,将数组包装在类中是个好主意,因此您不必记住每次创建时都删除它:

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);

But of course, someone has already done the work for you. 但当然,有人已经为你完成了这项工作。 Take a look at boost::multi_array . 看一下boost::multi_array

(S)He wants vectors as in physics. (S)他想要物理学中的矢量。

either roll your own as an exercise: 或者将自己作为练习:

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

or use libraries like Eigen which have Vector2f defined 或使用像Eigen这样定义了Vector2f的库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM