重载operator <relational C ++

问题描述 投票:-2回答:1

我试着回答这个问题,但我不能。可以帮助我.Vector3Ds是一个类,它接受数学中的x,y,z三维数学向量:

问题:假设您希望能够将Vector3D存储在STL集中。您将此任务委派给使用以下operator <的实现返回的朋友:

 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集或映射中,则operator <operator的实现将导致严重问题。为什么是这样? (提示:less-than运算符的数学属性是什么,它们都适用于这个实现吗?)。我尝试了上面的代码,看起来没问题。没有错误,元素按顺序排序。为什么问题说出来会造成严重的问题。

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;
 }
c++ operator-overloading operator-keyword
1个回答
2
投票

operator<的实施不符合strictly weak ordering要求的需要。

我们先来两点:

p1 = [1,2,0]和 p2 = [2,1,0]。

根据您的实现,p1 <p2和p2 <p1。在订购对象时,这将成为一个问题。

一种解决方案是使用:

bool Vector3D::operator<(const Vector3D& other) const
{
   for(int k = 0; k < NUM_COORDINATES; ++k)
   {
      if(coordinates[k] != other.coordinates[k])
      {
         return (coordinates[k] < other.coordinates[k]);
      }
   }
   return false;
}
© www.soinside.com 2019 - 2024. All rights reserved.