Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #include <algorithm>
- using namespace std;
- template <typename T>
- class Vector{
- private:
- // 資料(變數部分)
- T _x;
- T _y;
- public:
- // 操作(函式部分)
- Vector(){
- _x = 0;
- _y = 0;
- }
- Vector(T x, T y){
- _x = x;
- _y = y;
- }
- // this指標: 指向自己這個物件
- Vector& setX(T x){
- // (*this)._x = x;
- this->_x = x;
- return *this;
- }
- Vector& setY(T y){
- _y = y;
- return *this;
- }
- T getX() const{
- return _x;
- }
- T getY() const{
- return _y;
- }
- double length() const{
- return sqrt( _x * _x + _y * _y );
- }
- Vector operator+(const Vector &b) const{
- double newX = _x + b._x;
- double newY = _y + b._y;
- Vector c(newX, newY);
- return c;
- }
- bool operator<(const Vector &b) const{
- if( length() < b.length() ){
- return true;
- }
- else if( length() > b.length() ){
- return false;
- }
- else if( _x < b._x ){
- return true;
- }
- else if( _x > b._x ){
- return false;
- }
- else if( _y < b._y ){
- return true;
- }
- else if( _y > b._y ){
- return false;
- }
- else{
- return false;
- }
- }
- void print() const{
- cout << "(" << _x << "," << _y << ")" << endl;
- }
- };
- int main(){
- /*
- const Vector v(3, 4);
- cout << v.length() << endl;
- */
- /*
- Vector<double> a;
- Vector<double> b(-1.2, 6.3);
- a.setX(3).setY(4);
- Vector<double> answer = a + b;// a.operator+(b);
- answer.print();
- */
- Vector<int> array[] = { Vector<int>(3, 4), Vector<int>(4, 5), Vector<int>(1, 2), Vector<int>(3, 5), Vector<int>(1, 3)};
- sort(array, array+5);
- for( int i = 0 ; i < 5 ; i++ ){
- array[i].print();
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment