Shenzhen University Computer Software "Object-Oriented Programming" Experiment 14 Operator Overloading 2 and Function Templates

A. Date comparison (type conversion of operator overloading)

topic description

Define a date class CDate, including attributes: year, month, day, all integers.

The constructor contains a single parameter, the parameter is an eight-digit integer, the default value is 0, and the integer is converted into a date type, for example, if the parameter is 20170612, it is converted to year=2017, month=6, day=12

Implement conversion operator overloading to convert the date type to an integer, for example, June 8, 2017 is converted to 20170608. Note that if the month or day is less than 10, 0 should be added when converting to an integer

Realize the date output function Print, see the demonstration data for the specific format

The main function is as follows, it cannot be modified, please implement the date class above

int main()

{

int t, t1, t2;

CDate C1, C2;

cin>>t;

while (t–)

{cin>>t1>>t2;

C1 = t1;

C2 = t2;

((C1>C2)?C1:C2).Print(); //The output with a large date, in the code C1>C2, will automatically convert C1 and C2 into integers for comparison

}

return 0;

}

Note: This topic does not need or overload the > operator, as long as the conversion operator is overloaded, the date type can be converted to an integer.

enter

Enter t in the first line to indicate that there are t pairs of dates

Then enter two dates every two lines

Enter t pairs

output

Each line outputs a pair of dates, the date is the largest information

Input sample 1

2
20170630
20160528
19981111
20021212

output sample 1

June 30, 2017
December 12, 2002

AC code

//定义一个日期类CDate,包含属性:年、月、日,都是整数。
//
//构造函数含单个参数,参数是八位整数,默认值为0,实现整数转为日期类型,例如参数为20170612,转为year = 2017, month = 6, day = 12
//
//实现转换运算符重载,把日期类型转为整数,例如2017年6月8日转为20170608。注意,如果月或日小于10,转化为整数时要补0
//
//实现日期的输出函数Print,具体格式看示范数据
//
//主函数如下,不能修改,请实现上面的日期类
#include<bits/stdc++.h>
using namespace std;


class CDate {
    
    
	int y, m, d;

public:
	CDate(int t = 0) {
    
    
		if (!t) {
    
    
			y = m = d = 0;
			return;
		}	string temp = to_string(t);
		string year = temp.substr(0, 4);
		string month = temp.substr(4, 2);
		string day = temp.substr(6, 2);
		y = stoi(year);
		m = stoi(month);
		d = stoi(day);
	}

	operator int() {
    
    
		return y * 10000 + m * 100 + d;
	}

	void Print() {
    
    
		cout <<   y << "年"  << setfill('0') << setw(2) << m << "月" << setfill('0') << setw(2) << d << "日" << endl;
	}


	//CDate operator >(const CDate& c)const {
    
    
	//	CDate t1 = *this;
	//	CDate t2 = c;
	//	cout << t1 << " " << t2 << endl;

	//	return (int)t1 > (int)t2 ? t1 : t2;
	//}

};


int main()
{
    
    
	int t, t1, t2;
	CDate C1, C2;
	cin >> t;
	while (t--)
	{
    
    
		cin >> t1 >> t2;
		C1 = t1;
		C2 = t2;
		((C1 > C2) ? C1 : C2).Print(); //日期大的输出,在代码C1>C2中,会自动把C1和C2转换为整数进行比较
	}
	return 0;
}

B. Element lookup (function template)

topic description

Write a function template for searching in an array, where the array has n elements, the type is T, and the element to be searched is key.

Note: Template functions must be used

enter

Input t in the first line indicates that there are t test instances

In the second line, first enter an uppercase letter to indicate the array type, I to indicate the integer type, D to indicate the double precision number type, C to indicate the character type, and S to indicate the string type; then input n to indicate the length of the array.

Enter n data in the third line

Enter the key on the fourth line

Enter t instances in sequence

output

Output one result per line, find out which element the output key is in the array (starting from 1), and output 0 if not found

Input sample 1

4
I 5
5 3 51 27 9
27
D 3
-11.3 25.42 13.2
2.7
C 6
a b g e u q
a
S 4
sandy david eason cindy
cindy

output sample 1

4
0
1
4

AC code

#include<bits/stdc++.h>
using namespace std;

template<class T>
int Find(vector<T>& v, T key) {
    
    
	for (int i = 0; i < v.size(); i++) 
		if (v[i] == key)
			return i + 1;
	return 0;
}


int main() {
    
    
	int t;
	cin >> t;
	while (t--){
    
    
		char c;int n;
		cin >> c >> n;
		if (c == 'I') {
    
    
			vector<int>v(n);
			for (auto& i : v)
				cin >> i;
			int key;
			cin >> key;
			cout << Find(v,key) << endl;
		}
		else if (c == 'C') {
    
    
			vector<char>v(n);
			for (auto& i : v)
				cin >> i;
			char key;
			cin >> key;
			cout << Find(v, key) << endl;
		}
		else if (c == 'D') {
    
    
			vector<double>v(n);
			for (auto& i : v)
				cin >> i;
			double key;
			cin >> key;
			cout << Find(v, key) << endl;
		}
		else {
    
    
			vector<string>v(n);
			for (auto& i : v)
				cin >> i;
			string key;
			cin >> key;
			cout << Find(v, key) << endl;
		}
	}

	return 0;
}

C. Data sorting (function template)

topic description

Write a function template that sorts in ascending order, where the array has n elements and is of type T.

Note: Template functions must be used

enter

Input t in the first line indicates that there are t test instances

In the second line, first enter an uppercase letter to indicate the array type, I to indicate the integer type, C to indicate the character type, S to indicate the string type, and D to indicate the double precision number type; then input n to indicate the length of the array.

Enter n data in the third line

Enter t instances in sequence

output

Output one result per line

Input sample 1

4
I 10
15 3 51 27 9 35 78 14 65 8
D 3
-11.3 25.42 13.2
C 6
a b g e u q
S 4
sandy david eason cindy

output sample 1

3 8 9 14 15 27 35 51 65 78
-11.3 13.2 25.42
a b e g q u
cindy david eason sandy

AC code

#include<bits/stdc++.h>
using namespace std;

template<class T>
void bubbleSort(vector<T>& v) {
    
    
	int n = v.size();
	for (int i = 1; i < n; i++)
		for (int j = 0; j < n - i; j++)
			if (v[j] > v[j + 1])
				swap(v[j], v[j + 1]);
}

template<class T>
void print(vector<T>& v) {
    
    
	for (int i = 0; i < v.size(); i++) {
    
    
		cout << v[i] << " ";
	}
	cout << endl;
}

int main() {
    
    
	int t;
	cin >> t;
	while (t--) {
    
    
		char c; 
		int n;
		cin >> c >> n;
		if (c == 'I') {
    
    
			vector<int>v(n);
			for (auto& i : v)
				cin >> i;
			bubbleSort(v);
			print(v);

		}
		else if (c == 'C') {
    
    
			vector<char>v(n);
			for (auto& i : v)
				cin >> i;
			bubbleSort(v);
			print(v);

		}
		else if (c == 'D') {
    
    
			vector<double>v(n);
			for (auto& i : v)
				cin >> i;
			bubbleSort(v);
			print(v);

		}
		else {
    
    
			vector<string>v(n);
			for (auto& i : v)
				cin >> i;
			bubbleSort(v);
			print(v);
		}
	}

	return 0;
}

D. Who has the highest number of votes (function template)

topic description

A small town wants to vote for the mayor, and the one who gets the most votes is elected. However, due to the unsound voting mechanism, the identification code types of the candidates in the voting system are inconsistent during each voting. Please write a function template that can find the element with the highest votes for multiple types of data. Among them, there are n ballots for each voting session, and the identification code type is T

Note: Template functions must be used

enter

Input t in the first line indicates that there are t test instances

In the second line, first enter an uppercase letter to indicate the type of identification code, I to indicate the integer type, C to indicate the character type, and S to indicate the string type; then input n to indicate the length of the array.

Enter n data in the third line

Enter t instances in sequence

output

Output one result per line, output the identification code of the elected candidate and the number of votes, separated by spaces.

Input sample 1

3
I 10
5 3 5 2 9 7 3 7 2 3
C 8
a b a e b e e q
S 5
sandy david eason cindy cindy

output sample 1

3 3
e 3
cindy 2

AC code

#include<bits/stdc++.h>
using namespace std;

template<class T>
void func(vector<T>&v) {
    
    
	map<T, int>mapp;
	for (auto& ii : v) {
    
    
		mapp[ii]++;
	}

	T t = v[0];
	for (auto& it : v) {
    
    
		if (mapp[it] > mapp[t])
			t = it;
	}
	cout << t << " " << mapp[t] << endl;

}


int main() {
    
    
	int t;
	cin >> t;
	while (t--) {
    
    
		char c; 
		int n;
		cin >> c >> n;
		if (c == 'I') {
    
    
			vector<int>v(n);
			for (auto& i : v)
				cin >> i;
			func(v);
		}
		else if (c == 'C') {
    
    
			vector<char>v(n);
			for (auto& i : v)
				cin >> i;
			func(v);
		}
		else if (c == 'D') {
    
    
			vector<double>v(n);
			for (auto& i : v)
				cin >> i;
			func(v);
		}
		else {
    
    
			vector<string>v(n);
			for (auto& i : v)
				cin >> i;
			func(v);
		}
	}

	return 0;
}

E. Rectangular relations (operator overloading)

topic description

It is assumed that the coordinates adopt two-dimensional plane coordinates.

Define the point class CPoint, including attributes x, y (integer). The methods are: constructor with parameters, getX, getY return the x coordinate and y coordinate of the point respectively.

Define the rectangle class CRectangle, including attributes: coordinates leftPoint of the upper left corner of the rectangle, coordinates rightPoint of the lower right corner of the rectangle. The methods in the class are:

1) Constructor with parameters to initialize the upper left and lower right corners of the rectangle

2) Overload the > operator, the parameter is a CPoint point object, assuming p, if p is within the rectangle, return true, otherwise return false.

3) Overload the > operator, if the first rectangle contains the second rectangle (some boundaries can be equal), return true, otherwise return false. (requires that function call 2) to implement)

4) Overload the == operator to determine whether the two rectangles are consistent and return true or false.

5) Overload the * operator to determine whether the two rectangles overlap and return true or false.

6) Overload the type conversion operator, calculate the area of ​​the rectangle and return it, the area is an integer.

7) Overload the < operator to output the two corner coordinates and the area of ​​the rectangle, see the sample for the specific format.

Input 2 rectangles, calculate the area, and judge the relationship between the rectangles. The main function is as follows and cannot be modified.

insert image description here

Constructors and destructors can be added as needed.

enter

Testing frequency

Each set of test data is as follows:

Coordinates of upper left corner and lower right corner of rectangle 1

Coordinates of upper left corner and lower right corner of rectangle 2

output

Each set of test data is output as follows, separated by blank lines:

The coordinates and area of ​​rectangle 1 (see the sample for the specific format)

The coordinates and area of ​​rectangle 2 (see the sample for the specific format)

The relationship between rectangle 1 and rectangle 2 (rectangle 1 contains rectangle 2, rectangle 2 contains rectangle 1, rectangle 2 and rectangle 1 are equal, rectangle 1 and rectangle 2 intersect, rectangle 1 and rectangle 2 do not intersect)

Input sample 1

2
1 4 4 1
2 3 3 2
1 4 4 1
0 3 5 2

output sample 1

Rectangle 1: 1 4 4 1 9
Rectangle 2: 2 3 3 2 1
Rectangle 1 contains Rectangle 2

Rectangle 1: 1 4 4 1 9
Rectangle 2: 0 3 5 2 5
Rectangle 1 and Rectangle 2 intersect

AC code

#include<bits/stdc++.h>
using namespace std;

class CPoint {
    
    
	int x, y;
public:
	CPoint(int x, int y) :
		x(x), y(y) {
    
    
	}

	int getX() const {
    
     return x; }
	int getY() const {
    
     return y; }

	bool operator == (const CPoint& p)const {
    
    
		return x == p.getX() && y == p.getY();
	}

};

class CRectangle {
    
    
	CPoint leftPoint, rightPoint;
public:
	CRectangle(int x1, int y1, int x2, int y2) :
		leftPoint(x1, y1), rightPoint(x2, y2)
	{
    
    

	}

	bool operator > (const CPoint& p)const {
    
    
		return !(p.getX() < leftPoint.getX() || p.getX() > rightPoint.getX() || p.getY() > leftPoint.getY() || p.getY() < rightPoint.getY());
	}

	bool operator >(const CRectangle& c) const {
    
    
		return *this > c.leftPoint && *this > c.leftPoint;
	}

	bool operator ==(const CRectangle& c) const {
    
    
		return leftPoint == c.leftPoint && rightPoint == c.rightPoint;
	}

	bool operator * (const CRectangle& c) const {
    
    
		if (leftPoint.getX() > c.rightPoint.getX())
			return false;
		if (rightPoint.getX() < c.leftPoint.getX())
			return false;
		if (leftPoint.getY() < c.rightPoint.getY())
			return false;
		if (rightPoint.getY() > c.leftPoint.getY())
			return false;
		return true;

		//return *this > c.rightPoint || *this > c.leftPoint || c > leftPoint || c > rightPoint;
	}

	operator int() {
    
    
		return-(rightPoint.getX() - leftPoint.getX()) * (rightPoint.getY() - leftPoint.getY());
	}

	friend ostream& operator << (ostream& output, CRectangle& c) {
    
      //定义重载运算符“<<”
		output << c.leftPoint.getX() << " " << c.leftPoint.getY() << " " << c.rightPoint.getX() << " " << c.rightPoint.getY();
		return output;
	}

};

int main() {
    
    
	int t, x1, x2, y1, y2;
	cin >> t;
	while (t--)
	{
    
    
		cin >> x1 >> y1 >> x2 >> y2;
		CRectangle rect1(x1, y1, x2, y2);
		cin >> x1 >> y1 >> x2 >> y2;
		CRectangle rect2(x1, y1, x2, y2);

		cout << "矩形1:" << rect1 << " " << (int)rect1 << endl;
		cout << "矩形2:" << rect2 << " " << (int)rect2 << endl;

		if (rect1 == rect2)
			cout << "矩形1和矩形2相等" << endl;
		else if (rect2 > rect1)
			cout << "矩形2包含矩形1" << endl;
		else if (rect1 > rect2)
			cout << "矩形1包含矩形2" << endl;
		else if (rect1 * rect2)
			cout << "矩形1和矩形2相交" << endl;
		else
			cout << "矩形1和矩形2不相交" << endl;
		cout << endl;
	}
	return 0;
}

F. Stack assignment (operator overloading)

topic description

Define a stack class Stack to realize mutual assignment between stacks. The member top indicates the top pointer of the stack, max indicates the maximum length of the stack, and the inflate function indicates that when the data stored in the stack exceeds the maximum length of the stack, the length of the stack is expanded to ensure that data can continue to be inserted.

The basic form of the Stack class is as follows:

insert image description here

Requirements are as follows:

1. Implement the Stack class;

2. The push() function can always insert data. When the maximum length of the stack is exceeded, the inflate function is called to expand the maximum length of the stack.

3. Initialize two Stack objects, perform a pop operation on the second object, exchange the two objects, and output the contents of the stack.

enter

The first line enters the size of 2 stacks.

The second line inputs the elements of the first stack.

The third line inputs the elements of the second stack.

output

Output the pop operation of the second object, after the two objects are exchanged, the elements of each object.

Input sample 1

3 4
1 2 3
4 5 6 7

output sample 1

456
123

hint

34
12

AC code

#include<bits/stdc++.h>
using namespace std;

class Stack {
    
    
	int* sp, top, max;
	void inflate(int lenth) {
    
    
		int* s = new int[lenth];
		for (int i = 0; i < max; i++)
			s[i] = sp[i];
		delete[]sp;
		sp = s;
	}

public:
	Stack(int size = 10) {
    
    
		top = 0;
		max = size;
		sp = new int[size];
	}


	Stack(const Stack& s) {
    
    
		sp = new int[s.max];
		top = s.top;
		max = s.max;
		for (int i = 0; i < top; i++) {
    
    
			sp[i] = s.sp[i];
		}
	}



	int pop() {
    
    
		if (top == 0)
			return -1;
		top--;
		return sp[top];
	}

	void push(int value) {
    
    
		if (max == top) {
    
    
			inflate(max * 2);
			max *= 2;
		}
		sp[top++] = value;
	}

	Stack& operator=(Stack& rightValue) {
    
    
		delete[]sp;
		sp = new int[rightValue.max];
		for (int i = 0; i < top; i++)
			sp[i] = rightValue.sp[i];
		max = rightValue.max;
		top = rightValue.top;
		return *this;
	}

	void show() {
    
    
		for (int i = 0; i < top; i++)
			cout << sp[i];
		cout << endl;
	}




};

int main() {
    
    
	int n, m;
	cin >> n >> m;
	Stack s1(n), s2(m);
	for (int i = 0; i < n; i++) {
    
    
		int t;
		cin >> t;
		s1.push(t);
	}

	for (int i = 0; i < m; i++) {
    
    
		int t;
		cin >> t;
		s2.push(t);
	}

	s2.pop();
	//s1 : 1 2 3
	//s2: 4 5 6

	//swap(s1, s2);
	Stack t = s1;
	s1 = s2;
	s2 = t;

	s1.show();
	s2.show();


	return 0;
}

G. Collections (Operator Overloading)

topic description

A set is a whole composed of one or more definite elements. Set operations include union, intersection, relative complement, etc.

Intersection of sets A and B: A set consisting of the same elements that belong to A and belong to B.

The union of set A and set B: a set consisting of all elements belonging to set A or to set B.

Set B is the relative complement of set A, denoted as AB: the set consisting of elements that belong to A but not to B.

Assume set A = {10, 20, 30}, set B = {1, 10, 50, 8}. Then the union of A and B is {10, 20, 30, 1, 50, 8}, the intersection of A and B is {10}, and the relative complement of B to A is {20, 30}.

Define the integer collection class CSet, the attributes include: the number n of elements in the collection, and the integer pointer data stores the elements in the collection.

The methods are: overload output, and output the elements in the collection according to the sample format.

Overload the + operator to find the union of set A and set B, and return the result set.

Overload the - operator to find the relative complement of set B with respect to set A, and return the result set.

Overload the * operator to find the intersection of set A and set B, and return the result set.

The main function inputs the data of sets A and B, and calculates the union, intersection, and relative complement of the sets.

According to the title, you can add required member functions to the CSet class.

enter

Testing frequency

Each set of test data has two lines, the format is as follows:

The first line: the number of elements and elements of the set A

The second line: the number of elements and elements of the set B

output

The output of each set of test data is as follows:

First row: set A

Second row: set B

The third line: the union of A and B

Fourth row: the intersection of A and B

The fifth line: the union of the relative complement of B with respect to A and the relative complement of A with respect to B, namely (AB)+(BA)

Each set of test data is separated by a blank line.

Input sample 1

2
3 10 20 30
4 10 1 2 3
5 100 2 3 4 -10
6 -34 12 2 4 90 100

output sample 1

A:10 20 30
B:10 1 2 3
A+B:10 20 30 1 2 3
A*B:10
(A-B)+(B-A):20 30 1 2 3

A:100 2 3 4 -10
B:-34 12 2 4 90 100
A+B:100 2 3 4 -10 -34 12 90
A*B:100 2 4
(A-B)+(B-A):3 -10 -34 12 90

AC code

#include<bits/stdc++.h>
using namespace std;

class CSet {
    
    
	int* data;
	int n;

	bool check(int value)const {
    
    
		for (int i = 0; i < n; i++) {
    
    
			if (value == data[i])
				return true;
		}
		return false;
	}

	void push_back(int value) {
    
    
		data[n++] = value;
	}



public:
	CSet() {
    
    
		cin >> n;
		data = new int[n];
		for (int i = 0; i < n; i++)
			cin >> data[i];
	}

	CSet(int n1) {
    
     n = 0; data = new int[n1]; }

	CSet(const CSet& s) {
    
    
		n = s.n;
		data = new int[n];
		for (int i = 0; i < n; i++)
			data[i] = s.data[i];
	}



	CSet operator + (const CSet& s) const {
    
    
		CSet c(n + s.n);
		for (int i = 0; i < n; i++)
			if (!c.check(data[i]))
				c.push_back(data[i]);
		for (int i = 0; i < s.n; i++)
			if (!c.check(s.data[i]))
				c.push_back(s.data[i]);
		return c;
	}

	CSet operator - (const CSet& s) const {
    
    
		CSet c(n);
		for (int i = 0; i < n; i++)
			if (s.check(data[i]))
				continue;
			else if (!c.check(data[i]))
				c.push_back(data[i]);
		return c;
	}

	CSet operator * (const CSet& s) const {
    
    
		CSet c(n);
		for (int i = 0; i < n; i++)
			if (!s.check(data[i]))
				continue;
			else if (!c.check(data[i]))
				c.push_back(data[i]);
		return c;
	}


	void print() {
    
    
		for (int i = 0; i < n; i++)
		{
    
    
			if (i)cout << " ";
			cout << data[i];
		}
		cout << endl;
	}


	~CSet()
	{
    
    
		delete[]data;
	}

};


int main() {
    
    
	int t;
	cin >> t;
	while (t--) {
    
    
		CSet s1, s2;
		cout << "A:"; s1.print();
		cout << "B:"; s2.print();
		cout << "A+B:"; (s1 + s2).print();
		cout << "A*B:"; (s1 * s2).print();
		cout << "(A-B)+(B-A):"; ((s1 - s2) + (s2 - s1)).print();
		cout << endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_46655675/article/details/129334269