Sorting a vector of custom objects

后端 未结 13 3008
既然无缘
既然无缘 2020-11-21 05:14

How does one go about sorting a vector containing custom (i.e. user defined) objects.
Probably, standard STL algorithm sort along with a predicate (a fu

13条回答
  •  忘掉有多难
    2020-11-21 05:32

    typedef struct Freqamp{
        double freq;
        double amp;
    }FREQAMP;
    
    bool struct_cmp_by_freq(FREQAMP a, FREQAMP b)
    {
        return a.freq < b.freq;
    }
    
    main()
    {
        vector  temp;
        FREQAMP freqAMP;
    
        freqAMP.freq = 330;
        freqAMP.amp = 117.56;
        temp.push_back(freqAMP);
    
        freqAMP.freq = 450;
        freqAMP.amp = 99.56;
        temp.push_back(freqAMP);
    
        freqAMP.freq = 110;
        freqAMP.amp = 106.56;
        temp.push_back(freqAMP);
    
        sort(temp.begin(),temp.end(), struct_cmp_by_freq);
    }
    

    if compare is false, it will do "swap".

提交回复
热议问题