如何利用C++/STL vector的sort算法对元素是自定义类型进行排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何利用C++/STL vector的sort算法对元素是自定义类型进行排序相关的知识,希望对你有一定的参考价值。
自己写一个比较函数就可以了,作为第三个参数传到sort函数。
下面有个小例子:
#include <iostream>#include <vector>
#include <algorithm>
using namespace std;
class AbA
public:
int m_nA;
int m_nB;
AbA(int a, int b) : m_nA(a), m_nB(b)
;
ostream& operator << (ostream& os, const AbA& ra)
os << ra.m_nA << " " << ra.m_nB;
return os;
// 自己写的比较函数
bool newLess(const AbA& ra, const AbA& rb)
return (ra.m_nA < rb.m_nA );
int main()
vector<AbA> vecAbA;
vecAbA.push_back(AbA(1, 2));
vecAbA.push_back(AbA(7, 8));
vecAbA.push_back(AbA(5, 6));
vecAbA.push_back(AbA(3, 4));
sort(vecAbA.begin(), vecAbA.end(), newLess);
for (int i = 0; i < vecAbA.size(); i++)
cout << vecAbA[i] << " ";
return 0;
朋友,请【采纳答案】,您的采纳是我答题的动力,如果没有明白,请追问。谢谢。
参考技术A 你好,可以利用map实现。以下是代码,请参考://copyright@quark//date:2010-10-19#include#include#include#includeusingnamespacestd;voidpaixu(vector&ivec,inttopnum)//选出出现次数最多的topnum个,其余删除vector::iteratoriter=ivec.begin();mapm;for(iter;iter!=ivec.end();++iter)m[*iter]++;if(topnum>m.count())return;//循环遍历map对象,输出最多出现的元素for(inti=0;imaxPair;map::const_iteratoriter=m.begin();while(iter!=m.end())if((*iter).second>maxPair.second)maxPair=*iter;iter++;if(maxPair.second>0)coutivec;ivec.push_back(3);ivec.push_back(2);ivec.push_back(1);ivec.push_back(2);ivec.push_back(1);ivec.push_back(1);ivec.push_back(1);paixu(ivec,2);getchar(); 参考技术B #include <vector>#include <iostream>
#include <string>
#include <algorithm> //sort函数头文件
using namespace std;
class Student
public:
int m_num;
string m_name;
public:
Student(int n,string name)
:m_num(n),m_name(name)
void display() const
cout << "姓名:" << m_name << " ,学号:" << m_num << endl;
;
//自定义的比较函数,这里是对学号进行排序
static bool myCompare(const Student& a1,const Student& a2)
return a1.m_num <= a2.m_num;
int main()
//创建4个学生
vector<Student> classOne;
Student a1(2,"a");
classOne.push_back(a1);
Student a2(4,"b");
classOne.push_back(a2);
Student a3(5,"c");
classOne.push_back(a3);
Student a4(1,"d");
classOne.push_back(a4);
cout << "排序前:" << endl;
vector<Student>::iterator it = classOne.begin();
while (it != classOne.end())
it->display();
++it;
sort(classOne.begin(), classOne.end(),myCompare);
cout << "排序后:" << endl;
it = classOne.begin();
while (it != classOne.end())
it->display();
++it;
return 0;
以上是关于如何利用C++/STL vector的sort算法对元素是自定义类型进行排序的主要内容,如果未能解决你的问题,请参考以下文章
Codeblocks 调试(debug)如何查看 STL vector等容器的内容