只有一个字段很容易:
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