/***************************************************************************** *** FILE: sort_array.cpp *** DATE: 04/10/2004 *** AUTHOR: Daniel Dementiev *** GOAL: This short example illustrates how to sort managed array is MS *** Visual C++ managed extension. Please note how we create and use *** new class RobotComparer to specify a tool for comparing robots. *** To compile the project, use *** ...> cl array.cpp /clr *****************************************************************************/ #using using namespace System; __gc class Robot { private: static int curID = 1; int ID; int HP; // servce data members static Random *rnd = new Random; int rand(int max) { return rnd->Next(max)+1; }; public: Robot() : ID(curID++), HP(rand(100)) {}; ~Robot() {}; void PrintInfo() { Console::WriteLine(S"Robot {0} has {1} HP", ID.ToString(), HP.ToString() ); }; int getHP() { return HP; }; }; __gc struct RobotComparer : Collections::IComparer { int Compare(Object *a, Object *b) { Robot *left = dynamic_cast(a); Robot *right = dynamic_cast(b); return left->getHP() - right->getHP(); } }; void main() { int N = 10, i; Robot* robots[] = __gc new Robot*[N]; for(i=0;iLength;i++) robots[i]->PrintInfo(); Array::Sort(robots, new RobotComparer); Console::WriteLine(S"Sorted array:"); for(i=0;iLength;i++) robots[i]->PrintInfo(); }