Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

overload operator <

Status
Not open for further replies.

jl3574

Programmer
Jun 5, 2003
76
CA
i am writing a program which i want to compare object and sort them....

i have a class Shape which have sub classes Triangle , Circle and Rectangle....

i have store the shapes in a Vector list.
however i have tocompare the area in each shape and sort them...

i believe one way to do this is to use the "OVERLOAD OPERATOR < "
i don't quite understand how overload operators work.
i want to re assign < so that i can use bubble sort in my vector list and compare the two object's area and then swap then...

problem i'm having:
how do i define the overload operator in my class? and how do i swap 2 object in a vector list... can someone show me a quick example pls ..thx....
 
Here is some examples showing how to cope with operator< and the swapping of 2 items(of a vector) :
Code:
#include <assert.h>
#include <iostream>
#include <vector>
#include <string>

using namespace std;

//Root class of the inheritance tree
class Shape
{
public:
  virtual double area () const = 0;

  // define operator strictly less than
  virtual bool operator< (const Shape& other) const
  {
    return area () < other.area ();
  }
};

//A basic heir of class Shape
class Rectangle : public Shape
{
public:
  Rectangle (double long_edge, double small_edge) :
    _long_edge (long_edge),
    _small_edge (small_edge)
  {
    assert (long_edge >= small_edge);//arguments_coherence
  }

  virtual double area () const
  {
    return _long_edge * _small_edge;
  }

private:
  double _long_edge;
  double _small_edge;
};


//Some basic tests and how to swap two items of a vector
int main ()
{
  Rectangle r1 (5, 3);
  Rectangle r2 (8, 7);

  assert (r1 < r2);

  //shapes is a polymorphic data structure, so you need to have references.
  vector<Shape*> shapes;
  shapes.push_back (&r1);
  shapes.push_back (&r2);

  //swap items of indexes 0 and 1, use a temp variable
  Shape* temp_shape = shapes[0];
  shapes[0] = shapes[1];
  shapes[1] = temp_shape;

  //need to be dereferenced, otherwise addresses are compared
  assert (*shapes[1] < *shapes[0]);

  return 0;
}

You can directly test this code.

--
Globos
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top