C++ 2D vector and operations

别来无恙 提交于 2019-12-21 05:32:16

问题


How can one create a 2D vector in C++ and find its length and coordinates?

In this case, how are the vector elements filled with values?

Thanks.


回答1:


If your goal is to do matrix computations, use 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<double> > matrix;
matrix.resize(10);
matrix[0].resize(20);
// etc



回答2:


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(mat, mat + width * height, 42);

To fill it with arbitrary values use std::generate() or 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[] 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.




回答3:


(S)He wants vectors as in physics.

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



来源:https://stackoverflow.com/questions/4844810/c-2d-vector-and-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!