如何首先按一个属性而不是另一个属性对容器进行排序?

时间:2019-09-17 14:21:35

标签: c++ sorting containers std deque

只有一个字段很容易:

bool operator<(const MidiMsg &midiMsg) const {
    return (mPosition < midiMsg.mPosition);
}

但是,如果我需要先由一位成员订购,而不是由另一位订购,该怎么办?

尝试过:

bool operator<(const MidiMsg &midiMsg) const {
    return (mPosition < midiMsg.mPosition && mId < midiMsg.mId);
}

但似乎不起作用。

这是一个可行的示例:

#include <iostream>
#include <deque>
#include <algorithm>

struct MidiMsg {
    int mPosition;
    int mId;

    bool operator<(const MidiMsg &midiMsg) const {
        return (mPosition < midiMsg.mPosition && mId < midiMsg.mId);
    }
};

int main() {
    std::cout.precision(10);

    std::deque<MidiMsg> mNotes;

    MidiMsg note;

    note.mPosition = 0;
    note.mId = 1;
    mNotes.push_back(note);

    note.mPosition = 44100;
    note.mId = 1;
    mNotes.push_back(note);

    note.mPosition = 0;
    note.mId = 0;
    mNotes.push_back(note);

    note.mPosition = 44100;
    note.mId = 0;
    mNotes.push_back(note);

    note.mPosition = 0;
    note.mId = 2;
    mNotes.push_back(note);

    note.mPosition = 44100;
    note.mId = 2;
    mNotes.push_back(note);    

    std::sort(mNotes.begin(), mNotes.end());

    for (size_t index = 0; index < mNotes.size(); index++) {
        std::cout << mNotes[index].mPosition << " - " << mNotes[index].mId << std::endl;
    }
}

哪个输出:

0 - 1
0 - 0
44100 - 1
44100 - 0
0 - 2
44100 - 2

而不是:

0 - 0
0 - 1   
0 - 2   
44100 - 0   
44100 - 1
44100 - 2

0 个答案:

没有答案