【发布时间】:2018-05-30 03:03:22
【问题描述】:
我试图回答这个问题但我不能。你能帮帮我吗。Vector3Ds 是一个类,它在一个数组中接受像 x,y,z 这样的 3d 数学向量:
问题: 假设您希望能够将 Vector3D 存储在 STL 集中。您将此任务委托给一个朋友,他返回以下操作符 <:> 的实现
bool Vector3D::operator< (const Vector3D& other) const
{
for(int k = 0; k < NUM_COORDINATES; ++k)
if(coordinates[k] < other.coordinates[k]) return true;
return false;
}
如果 Vector3D 存储在 STL 集或地图中,则运算符
Vector3D.h
class Vector3D
{
public:
Vector3D();
void set(int arrayIndex,int num);
bool operator< (const Vector3D& other) const;
private:
static const int NUM_COORDINATES = 3;
double coordinates[NUM_COORDINATES];
};
Vector3D.cpp
#include "Vector3D.h"
Vector3D::Vector3D(void){
}
void Vector3D::set(int arrayIndex,int num){
coordinates[arrayIndex]=num;
}
bool Vector3D::operator< (const Vector3D& other) const
{
for(int k = 0; k < NUM_COORDINATES; ++k)
if(coordinates[k] < other.coordinates[k]) return true;
return false;
}
【问题讨论】:
-
如果您测试了代码并且没有遇到问题,那么您的测试不是很好。根据您对
operator<的定义,您需要插入严格弱irder 的条件不成立的值。哪些值会导致问题完全取决于您使用对象的类/函数。 -
计算向量的长度并在比较中使用它,而不是比较坐标。
标签: c++ operator-overloading operator-keyword