Write a comparison object that uses the square of an objects value for comparison. Therefore, a large negative number is greater than a small positive number using this comparison object. Generate in a vector the integers -100 to +100 and use an STL sort with this comparison object. Print out the result.
编写一个比较对象,该对象使用对象的平方值进行比较。因此,使用该比较对象后,一个大的负数比一个小的正数要大。在vector中产生-100~+100的整数,并使用这个排序对象调用STL的排序算法,打印最终结果。
//本程序在VCSP6下编译通过
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class compare
{
public:
bool operator()(const int &x,const int &y)
{
return (x*x)>(y*y);
};
};
int main()
{
vector<int> v;
compare cmp;
for(int i=-100;i<101;i++)
v.push_back(i);
cout<<"下面打印未排序前v中的元素:"<<endl;
for(i=0;i<v.size();i++)
cout<<v[i]<<'\t';
cout<<endl;
sort(v.begin(),v.end(),cmp);
cout<<"下面打印排序后的元素:"<<endl;
for(i=0;i<v.size();i++)
cout<<v[i]<<'\t';
return 0;
}