用于表示点\位置的类型或向量
我有一系列不会改变的点\位置。我应该表示为整数向量还是新类型?
我目前的偏好是使用向量:
doSomething(myVec[0], myVec[1] );
doSomethingElse(myVec[2], myVec[3] );
而不是:
doSomething( myType.getPos1(), myType.getPos2() );
doSomethingElse( myType.getPos3(), myType.getPos4() );
有任何想法或想法吗?
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么不创建一个实际的向量结构/类?
我所说的向量是指数学向量。通常向量用于点和位置。这样做的好处是你的代码将更具可读性。
游戏、图形和其他应用程序就是这样做的。使用相关数据的列表不是 OO,这也是 OOP 存在的原因之一。
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.
恕我直言,最佳解决方案是:
[...其他地方...]
(我的 C++ 很生锈,可能不是正确的语法)
The IMHO optimal solution would be:
[... somewhere else ...]
(My C++ is rusty, might not be correct syntax)
由于您使用的是
stl
,我会使用vector
对 >
(如果点不是整数,则为vector >
)。它非常适合积分。那么你可以这样做:
Since you're using
stl
, I'd usevector< pair<int,int> >
(orvector< pair<double,double> >
if the points aren't integer). It works great for points.So then you could do something like this:
如果您需要迭代它们,那么答案是显而易见的。
如果它们没有改变并且您可以管理复杂性,那么第一个选项就可以了。第二个可能更具可读性(如果您选择好的名称)。
您还可以编写一个包含或保存对向量的引用的类。在这种情况下,您可以同时获得两者的好处。
您还可以使用 Boost.tuple 库。
并通过以下方式访问它们:
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.
and access them as:
根据给定的信息很难说。但根据到目前为止提供的任何信息,我更愿意使用
x
和y
坐标编写一个struct Point
并创建一个点的向量。这将为您带来将对象存储在标准容器中的好处,而且它会在逻辑上将数据绑定在通用结构中,这样您就不必每次都
vec[0],vec[1]
当你想要一个点的时候。附带说明一下,如果您使用getPos
方法编写类,我肯定会编写getPos(int index)
而不是getPos1
,getPos2
等Its difficult to say with the given information. But with whatever information provided so far, I would prefer to write a
struct Point
withx
andy
co-ordinates and create avector
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 tovec[0],vec[1]
every time when you want a point. As a side note, if you are writing the class withgetPos
method I would certainly writegetPos(int index)
rather thangetPos1
,getPos2
etc.