Simplicity
Simplicity

Reputation: 48916

C++ 2D vector and operations

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.

Upvotes: 3

Views: 14012

Answers (3)

anon
anon

Reputation: 11

(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

Upvotes: 1

wilhelmtell
wilhelmtell

Reputation: 58677

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.

Upvotes: 3

chrisaycock
chrisaycock

Reputation: 37930

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

Upvotes: 5

Related Questions