Function object

#ifndef _SHAPE_H_
#define _SHAPE_H_
#include <iostream>
using namespace std;

class Shape{
public:
	virtual double area() const = 0;
	virtual double perimeter() const = 0;
};
class Square;
class Rectangle: public Shape{
private:
	double _length;
	double _width;
public:
	friend Square;
	friend ostream& operator<<(ostream& out, const Rectangle& src);
	Rectangle(double len = 0, double wid = 0){
		_length = len;
		_width = wid;
	}
	double get_len() const {
		return _length;
	}
	double get_wid() const {
		return _width;
	}
	void set_len(int len){
		_length = len;
	}
	void set_wid(int wid){
		_width = wid;
	}
	Rectangle(const Rectangle& src);
	virtual double area() const{
		return _length * _width;
	}
	virtual double perimeter()const{
		return 0;
	}
	void print(ostream& out) const {
		out<<"("<<_length<<", "<<_width<<")";
	}
};

class Square: public Rectangle {
public:
	Square(double len) : Rectangle(len, len){
	}
	Square(const Square& src) {
		set_len(src.get_len());
		_length = src._length;
	}

};

ostream& operator<<(ostream& out, const Rectangle& src) {
	//src.print(out);
	out<<"("<<src._length<<", "<<src._width<<")";
	return out;
}
#endif


##############

#include "shape.h"
#include <vector>


class Compare_len {
public:
	bool operator()(const Rectangle& src1, const Rectangle& src2){
		return src1.get_len() > src2.get_len();
	}
};

class Compare_wid {
public:
	bool operator()(const Rectangle& src1, const Rectangle& src2){
		return src1.get_wid() > src2.get_wid();
	}
};

class Compare_area {
public:
	bool operator()(const Rectangle& src1, const Rectangle& src2){
		return src1.area() > src2.area();
	}
};


template<class Comparator>
int bubble_sort(vector<Rectangle>& data, Comparator is_bigger) {
	int i = 0;
	int j = 0;
	int flag = 0;

	for(i = 0; i < data.size(); i++) {
		flag = 0;
		for(j = 0; j < data.size() - i - 1; j++) {
			if(is_bigger(data[j], data[j+1])) {
				swap(data[j], data[j+1]);
				flag = 1;
			}
		}
		if(flag == 0) break;
	}
	return 0;
}

Rectangle::Rectangle(const Rectangle& src){
		_length = src._length;
		_width = src._width;
	}


int main(){
	Rectangle a1(1,4), a2(2,3), a3(2,2), a4(3, 1), a5(4,1);
	vector<Rectangle> vec;

	vec.push_back(a1);
	vec.push_back(a2);
	vec.push_back(a3);
	vec.push_back(a4);
	vec.push_back(a5);


	bubble_sort(vec, Compare_wid());
	for(int i = 0; i < vec.size(); i++) {
		cout<<vec[i]<<endl;

	}

	return 0;
}


 

 

 

 

 


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章