zoukankan      html  css  js  c++  java
  • Practice3_4_vector_sort_struct_string

    一个string的compare函数,搞定字符串排序,哈哈!!

    下一版本将全面补充,首先按照运动员的姓名升序排序,其次按照运动员金银铜数量降序排序。

    // Practice3_vector_sort_struct.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"
    #include <vector>
    #include <algorithm>
    #include <iostream>
    #include <ctime>
    #include <stdio.h>
    #include <string>

    using namespace std;

    struct ScoreStruct
    {
    string name;
    unsigned int chinese;
    unsigned int math;
    unsigned int english;
    bool operator <(const ScoreStruct &right) const
    {
    int temp = name.compare(right.name);
    if( temp < 0)//大于0,是降序;若要升序,则小于0;不管是string的compare,还是int整型值!!
    {
    return 1;
    }
    else
    {
    return 0;
    }
    }
    };

    string strs[4] = { "tencent", "google","alibaba", "facebook"};

    void initVector(vector<ScoreStruct> &vec, unsigned int size)
    {
    srand(unsigned(time(NULL)));
    for(unsigned int i =0; i < size; i++)
    {
    char buff[32] = {0};
    int chineseScore = rand()%100;
    int mathScore = rand()%100;
    int englishScore = rand()%100;
    //sprintf(buff, "%d", chineseScore);
    ScoreStruct ss = {strs[i], chineseScore, mathScore, englishScore};
    /*
    ScoreStruct ss = {"0", 0};
    strcpy(ss.name, buff);
    ss.score = randNum;
    */
    vec.push_back(ss);
    }
    }

    void printVector(vector<ScoreStruct> vec)
    {
    vector<ScoreStruct>::iterator it = vec.begin();
    for(; it != vec.end();++it)
    {
    cout << it->name << "," << it->chinese << "," << it->math << "," << it->english << " ";
    }
    cout<<endl;
    }

    int _tmain(int argc, _TCHAR* argv[])
    {
    vector<ScoreStruct> vect;
    initVector(vect, 4);
    cout<<"before sort"<<endl;
    printVector(vect);
    sort(vect.begin(), vect.end());
    cout<<"after sort"<<endl;
    printVector(vect);
    return 0;
    }

    C++的string的compare函数看这里:http://www.cplusplus.com/reference/string/string/compare/

  • 相关阅读:
    Scrapy抓取Quotes to Scrape
    pyspider爬取TripAdvisor
    [转]Python爬虫框架--pyspider初体验
    使用代理处理反爬抓取微信文章
    控制流程语句
    【bzoj3029】守卫者的挑战 概率dp
    【bzoj4994】[Usaco2017 Feb]Why Did the Cow Cross the Road III 树状数组
    【bzoj4952】[Wf2017]Need for Speed 二分
    【bzoj5047】空间传送装置 堆优化Dijkstra
    【bzoj5055】膜法师 离散化+树状数组
  • 原文地址:https://www.cnblogs.com/liuzc/p/6485961.html
Copyright © 2011-2022 走看看