C++ 学习笔记8

本文介绍了一种使用对象值的平方来进行比较的方法,使得大的负数比小的正数更大。通过实现一个自定义比较类并利用STL的sort函数,生成了-100到+100之间的整数序列并按此规则排序。
 

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值