zoukankan      html  css  js  c++  java
  • vector对自定义结构体排序注意2点

    // testStl.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <utility>
    #include <functional>
    #include <string>
    
    using namespace std;
    
    struct test_large : public binary_function<int, int, bool>
    {
        bool operator()(int x, int y)
        {
            return (x > y);
        }
    };
    
    /* 要对结构体进行排序,重载比较操作符就行了,然后结构体就可以像基础类型一样操作了*/
    typedef struct tagWorker
    {
        int age;
        string name;
    
        bool operator < (const tagWorker &y) const
        {
            return (age < y.age);
        }
    
        bool operator > (const tagWorker &y) const
        {
            return (age > y.age);
        }
    }Worker;
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        vector<int> v1;
    
        v1.push_back(2);
        v1.push_back(5);
        v1.push_back(3);
        v1.push_back(4);
        v1.push_back(1);
    
        v1[3] = 10; 
    
        vector<int>::iterator iter;
        for(iter = v1.begin(); iter != v1.end(); iter++)
        {
            cout<<*iter<<", ";
        }
    
        cout<<endl;
    
        sort(v1.begin(), v1.end(), less_equal<int>());
        for(iter = v1.begin(); iter != v1.end(); iter++)
        {
            cout<<*iter<<", ";
        }
    
        cout<<endl;
    
        sort(v1.begin(), v1.end(), test_large());
        for(iter = v1.begin(); iter != v1.end(); iter++)
        {
            cout<<*iter<<", ";
        }
    
        cout<<endl;
    
        vector<int> v2(2);
        v2[0] = 1;
        v2[1] = 2;
    
        /* 坑:指定大小方式使用数组,数组中的所有数据都必须要初始化,否则sort会报异常 */
        /* 这个地方也是个坑,如果v2初始化成100个,但只对部分赋值了,编译的时候不会报错,但运行的时候,sort函数会报异常*/
        sort(v2.begin(), v2.end(), less_equal<int>());
    
        cout<<v2[0]<<", "<<v2[1]<<endl;
    
        vector<Worker> v3(3);
        v3[0].age = 25;
        v3[0].name = "susu";
        v3[1].age = 18;
        v3[1].name = "chaochao";
        v3[2].age = 28;
        v3[2].name = "minmin";
    
        //sort(v1.begin(), v1.end(), less_equal<Worker>());
        sort(v3.begin(), v3.end(), less<Worker>());
    
        for(int index = 0; index < v3.size(); index++)
        {
            cout<<v3[index].age<<", "<< v3[index].name<<endl;
        }
    
        cout<<endl;
    
        sort(v3.begin(), v3.end(), greater<Worker>());
    
        for(vector<Worker>::const_iterator iter = v3.begin(); iter != v3.end(); iter++)
        {
            cout<<iter->age<<", "<<iter->name<<endl;
        }
    
        return 0;
    }
  • 相关阅读:
    《20170920-构建之法:现代软件工程-阅读笔记1》
    结对-贪吃蛇项目-开发过程
    个人-GIT使用方法
    团队-爬取豆瓣电影TOP250-开发环境搭建过程
    团队-爬取豆瓣电影TOP250-简单团队一阶段互评
    团队-爬虫电影网站-开发文档
    结对-贪吃蛇游戏-结对项目总结
    课后作业-阅读任务-阅读提问
    结对-贪吃蛇游戏-开发环境搭建过程
    结对编程贪吃蛇项目-结对编项目设计文档
  • 原文地址:https://www.cnblogs.com/liuzc/p/6542698.html
Copyright © 2011-2022 走看看