• Practice3_2_vector_sort_struct


    与前面只有结构体的name声明不同,初始化不同!!

    // 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
    {
    char name[32]; //和上个例子不同,这里声明由string name改为char name[32]
    unsigned int score;
    bool operator <(const ScoreStruct &right) const
    {
    return score < right.score;
    }
    };

    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 randNum = rand()%100;
    sprintf(buff, "%d", randNum);
    //ScoreStruct ss = {buff, randNum};//声明改了,此句不再能初始化,改为下面初始化
    ScoreStruct ss = {"0", 0};
    strcpy(ss.name, buff);// 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->score << " ";//声明由string name改为char name[32],此句仍然可以工作

    printf("%d,", it->score);
    printf("%s ", it->name);//声明由string name改为char name[32],此句可以工作了,printf打印字符串必须是首地址,printf必须是纯C,string是C++,所以不行
    }
    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;
    }

    printf

  • 相关阅读:
    励志
    哈佛大学用这12张图,教育了10亿人
    5分钟弄懂Docker!
    第四节:Web爬虫之pyquery解析库
    第十节:numpy之数组文件操作
    第三节:Web爬虫之BeautifulSoup解析库
    国嵌内核驱动进阶班-7-1(Ioctl设备控制)
    国嵌内核驱动进阶班-6-4 竞争与互斥(2)
    国嵌内核驱动进阶班-6-4 竞争与互斥
    C++类对象的内存结构
  • 原文地址:https://www.cnblogs.com/liuzc/p/6476658.html
Copyright © 2020-2023  润新知