/*
std::sort() 如何自定义比较函数 进行排序 。
Parameters
first, last - the range of elements to sort
policy - the execution policy to use. See execution policy for details.
comp - comparison function object (i.e. an object that satisfies the requirements of Compare) which returns true if the first argument is less than (i.e. is ordered before) the second.
The signature of the comparison function should be equivalent to the following:
//比较函数定义规则如下
bool cmp(const Type1 &a, const Type2 &b);
The signature does not need to have const &, but the function object must not modify the objects passed to it.
The types Type1 and Type2 must be such that an object of type RandomIt can be dereferenced and then implicitly converted to both of them.
*/
#include "stdafx.h"
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
struct STest
{
int m_age;
std::string m_strName;
};
typedef std::vector<STest>CVector;
//升序
bool compareAsc(const STest &value1,const STest &value2)
{
return value1.m_age > value2.m_age;
}
//降序
bool compareDes(const STest &value1,const STest &value2)
{
return value1.m_age < value2.m_age;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::cout<<"原始数据\n";
CVector vecTest;
for (int i = 0; i < 10; i++)
{
STest tmp;
tmp.m_age = i;
char ch[260]={0};
sprintf(ch,"%dhello",i);
tmp.m_strName = std::string(ch);
vecTest.push_back(tmp);
std::cout<<"age: "<<tmp.m_age <<"\tname: "<<tmp.m_strName.c_str()<<endl;
}
std::cout<<"==============================\n";
std::cout<<"升序序排序\n";
std::sort(vecTest.begin(),vecTest.end(),compareAsc);
CVector::iterator iter = vecTest.begin();
for (iter; iter != vecTest.end(); iter++)
{
std::cout<<"age: "<<iter->m_age <<"\tname: "<<iter->m_strName.c_str()<<endl;
}
std::cout<<"==============================\n";
std::cout<<"降序排序\n";
std::sort(vecTest.begin(),vecTest.end(),compareDes);
iter = vecTest.begin();
for (iter; iter != vecTest.end(); iter++)
{
std::cout<<"age: "<<iter->m_age <<"\tname: "<<iter->m_strName.c_str()<<endl;
}
return 0;
}
std::sort() 如何自定义比较函数 进行排序 。
最新推荐文章于 2024-06-09 13:38:10 发布