Tuesday, June 7, 2016
[C++] Custom sort
----------------- test.h --------------------#ifndef _TEST_H_
#define _TEST_H_
#include
using namespace std;
class XY
{
private:
int _x, _y, _value;
public:
XY() {};
XY(int x, int y, int value) { _x = x; _y = y; _value = value; }
~XY() {}
int X() const { return _x; }
int Y() const { return _y; }
int value() const { return _value; }
void SetValues(int x, int y, int value) { _x = x; _y = y; _value = value; }
// < operator overloading
// x-coordination has first priority, then y-coordingation
bool operator<(const XY &xy) const;
friend const ostream& operator<<(ostream &os, const XY &xy);
};
#endif
------------------- test.cpp ----------------------
#include "test.h"
using namespace std;
bool XY :: operator<(const XY &xy) const
{
if( _x < xy.X() ) return true;
else if( _x == xy.X() )
{
if( _y < xy.Y() ) return true;
else return false;
}
return false;
}
const ostream& operator<<(ostream &os, const XY &xy)
{
os << "(" << xy._x << "," << xy._y << ") -> " << xy._value ;
return os;
}
----------------------- main.cpp --------------------------
#include "test.h"
#include
#include
using namespace std;
int main()
{
vector vec_xy;
XY t;
t.SetValues(1,1,1);
vec_xy.push_back(t);
t.SetValues(2,2,4);
vec_xy.push_back(t);
t.SetValues(1,2,3);
vec_xy.push_back(t);
t.SetValues(2,1,3);
vec_xy.push_back(t);
for( int i = 0 ; i < vec_xy.size() ; i++ )
{
cout << vec_xy[i] << endl;
}
cout << "---------- sort -------------" << endl;
sort(vec_xy.begin(), vec_xy.end());
for( int i = 0 ; i < vec_xy.size() ; i++ )
{
cout << vec_xy[i] << endl;
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment