zoukankan      html  css  js  c++  java
  • 结构体排序的两种方法

    一、自定义比较函数

    #include <iostream>
    #include <algorithm>
    using namespace std;
    struct Node{
    	string name;
    	int age;
    };
    
    bool cmp(const Node a, const Node b)
    {
    	return a.age < b.age; // < 就是前面的小于后面的,即从小到大排序 
    }
    
    int main()
    {
    	struct Node nodes[3];
    	nodes[0].name = "zhang";
    	nodes[0].age = 18;
    	
    	nodes[1].name = "wang";
    	nodes[1].age = 20;
    	
    	nodes[2].name = "li";
    	nodes[2].age = 19;
    	
    	
    	sort(nodes, nodes + 3, cmp);
    	
    	
    	for(int i = 0; i < 3; ++i) {
    		cout << nodes[i].age << endl;
    	}
    } 
    

    二、结构体内嵌比较函数

    #include <iostream>
    #include <algorithm>
    using namespace std;
    struct Node{
    	string name;
    	int age;
    	
    	// 这里是cpp的运算符重载,重载了 <  
    	bool operator < (const Node& a) const
    	{
    		return age < a.age;  // < 就是从小到大排序 
    	} 
    };
    
    
    int main()
    {
    	struct Node nodes[3];
    	nodes[0].name = "zhang";
    	nodes[0].age = 18;
    	
    	nodes[1].name = "wang";
    	nodes[1].age = 20;
    	
    	
    	nodes[2].name = "li";
    	nodes[2].age = 19;
    	
    	
    	sort(nodes, nodes + 3);
    	
    	
    	for(int i = 0; i < 3; ++i) {
    		cout << nodes[i].age << endl;
    	}
    } 
    
  • 相关阅读:
    django–url
    SQLServer-镜像配置
    linux-阿里云ECS部署PPTP(centos)
    linux- svn服务器
    python(7)– 类的反射
    python(7)–类的多态实现
    python(6)-shutil模块
    python(6)-执行shell命令
    python(6)-类
    nagios–配置文件
  • 原文地址:https://www.cnblogs.com/VanHa0101/p/14317765.html
Copyright © 2011-2022 走看看