Robben_Ford_Fan_boy
Robben_Ford_Fan_boy

Reputation: 8730

Type or Vector for representing points\positions

I have a series of points\positions that won't change. Should I represent as Vector of ints or as a new type?

My preference at the moment is to go with vector:

doSomething(myVec[0], myVec[1] );
doSomethingElse(myVec[2], myVec[3] );

as opposed to:

doSomething( myType.getPos1(), myType.getPos2() );
doSomethingElse( myType.getPos3(), myType.getPos4() );

Any thoughts or ideas?

Thanks

Upvotes: 1

Views: 543

Answers (5)

Eddy Pronk
Eddy Pronk

Reputation: 6705

If you need to iterate over them then the answer is obvious.

If they don't change and you can manage the complexity then the first option is fine. The second might be more readable (if you choose good names).

You can also write a class that contains or holds a reference to the vector. In that case you can have the benefits of both.

You could also use the Boost.tuple library.

#include <boost/tuple/tuple.hpp>

boost::tuple<int,int,int,int> position;

and access them as:

position.get<N>(); // where N is in 1,2,3,4

Upvotes: 1

user253984
user253984

Reputation:

The IMHO optimal solution would be:

struct Point {
  int x, y;
};

[... somewhere else ...]

vector<Point> points();

(My C++ is rusty, might not be correct syntax)

Upvotes: 3

dcp
dcp

Reputation: 55458

Since you're using stl, I'd use vector< pair<int,int> > (or vector< pair<double,double> > if the points aren't integer). It works great for points.

So then you could do something like this:

vector< pair<int,int> > points;
points.push_back(make_pair(1,2));
points.push_back(make_pair(2,2));

Upvotes: 2

Finglas
Finglas

Reputation: 15709

Why not create an actual vector struct/class?

By vector I mean a mathematical vector. Typically vectors are used for points and positions. A bonus of this is that your code will be much more readable.

This is how games, graphics and other applications do it. Using a list for related data is not OO, and one of the reasons OOP exists.

Upvotes: 3

Naveen
Naveen

Reputation: 73473

Its difficult to say with the given information. But with whatever information provided so far, I would prefer to write a struct Point with x and y co-ordinates and create a vector of the points. This will give you the benefits of storing the objects in a standard container plus it will logically bind the data in a common structure so that you don't have to vec[0],vec[1] every time when you want a point. As a side note, if you are writing the class with getPos method I would certainly write getPos(int index) rather than getPos1, getPos2 etc.

Upvotes: 3

Related Questions