#include "stdafx.h"
using namespace System;
using namespace System::Collections;
using namespace System::Globalization;
public value struct Vector: public IComparable
{
property double X;
property double Y;
property double Magnitude
{
double get()
{
return Math::Sqrt(X*X + Y*Y);
}
}
virtual int CompareTo(Object^ obj)
{
Vector^ v = *dynamic_cast<Vector^>(obj);
if ( v )
{
if ( this->Magnitude == v->Magnitude )
return 0;
else if ( this->Magnitude < v->Magnitude )
return -1;
else
return 1;
}
else
throw gcnew ArgumentException(
"Vector::CompareTo: obj must be of type 'Vector'");
}
// Comparison operators
static bool operator ==(Vector a, Vector b)
{
return a.X == b.X && a.Y == b.Y;
}
static bool operator !=(Vector a, Vector b)
{
return a.X != b.X || a.Y == b.Y;
}
static bool operator >(Vector a, Vector b)
{
return a.Magnitude > b.Magnitude;
}
static bool operator <(Vector a, Vector b)
{
return a.Magnitude < b.Magnitude;
}
// Misc required overloads
virtual bool Equals(Object^ obj) override
{
Vector^ compareTo = dynamic_cast<Vector^>(obj);
if ( compareTo )
{
return *this == *compareTo;
}
else
{
return false;
}
}
virtual int GetHashCode() override
{
return X.GetHashCode() ^ Y.GetHashCode();
}
virtual String^ ToString() override
{
return String::Format(CultureInfo::CurrentCulture->NumberFormat,
"[{0}, {1}]", X, Y);
}
};
void main()
{
array<Vector>^ data = gcnew array<Vector>(10);
// Sorting test
Random^ random = gcnew Random();
for ( int i = 0; i < data->Length; i++ )
{
data[i].X = random->NextDouble();
data[i].Y = random->NextDouble();
}
Array::Sort(data);
for ( int i = 0; i < data->Length; i++ )
{
Console::WriteLine("data[{0}]={1}", i, data[i].Magnitude);
}
}
|