【TOJ 5239】C++实验:复数排序(重载类排序的模板)

描述

定义:复数的实部与虚部的平方和的正的平方根的值称为该复数的模。

给定若干个复数,按照模从小到大排序,若两个复数模相等,则按照实部从小到大排序,若实部也相等,则按照虚部从小到大排序。

主函数里的代码已经给出,请补充完整,提交时请勿包含已经给出的代码。

int main()
{
	vector<Complex> vec;
	int n;
	while(cin>>n)
	{
		vec.clear();
		while(n--)
		{
			Complex c;
			cin>>c;
			vec.push_back(c);
		}
		sort(vec.begin(), vec.end());
		vector<Complex>::iterator it;
		for(it=vec.begin();it!=vec.end();it++)
		{
			cout<<*it<<endl;
		}
	}	
	return 0;
}

输入

输入数据有多组,每组的第一行为正整数n(n<=100),接下来有n行,每行两个整数,表示一个复数的实部和虚部。

输出

每组输出排序后的n个复数,每个复数占一行,只需输出实部和虚部值,用空格隔开。

样例输入

4
1 2
2 1
3 4
-1 -2

样例输出

-1 -2
1 2
2 1
3 4

#include<bits/stdc++.h>
using namespace std;
class Complex{
public:
    int a,b;//a实部 b虚部
    double m;
    bool friend operator<(const Complex&x,const Complex&y)
    {
        if(x.m!=y.m)
        {
            if(x.m<y.m)
                return true;
            else return false;
        }
        else if(x.a!=y.a)
        {
            if(x.a<y.a)
                return true;
            else return false;
        }
        else if(x.b!=y.b)
        {
            if(x.b<y.b)
                return true;
            else return false;
        }
    }
    friend istream&operator>>(istream&is,Complex&x)
    {
        is>>x.a>>x.b;
        x.m=sqrt(x.a*x.a+x.b*x.b);
        return is;
    }
    friend ostream&operator<<(ostream&os,const Complex&x)
    {
        os<<x.a<<" "<<x.b;
        return os;
    }
};
int main()
{
    vector<Complex> vec;
    int n;
    while(cin>>n)
    {
        vec.clear();
        while(n--)
        {
            Complex c;
            cin>>c;
            vec.push_back(c);
        }
        sort(vec.begin(), vec.end());
        vector<Complex>::iterator it;
        for(it=vec.begin();it!=vec.end();it++)
        {
            cout<<*it<<endl;
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/kannyi/p/9049648.html