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;
}