Warum this:Wie funktioniert std :: sort für eine Liste von Paaren?
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<pair<int, string>> list;
int main() {
int one = 1, two = 2, three =3, five =5, six = 6;
string bla = "bla";
list.push_back(pair<int, string>(two, bla));
list.push_back(pair<int, string>(one, bla));
list.push_back(pair<int, string>(two, bla));
list.push_back(pair<int, string>(six, bla));
list.push_back(pair<int, string>(five, bla));
sort(list.begin(), list.end());
for(auto item : list) {
cout << item.first << endl;
}
}
Arbeit als gedacht? Ausgang:
1
2
2
5
6
Wie std::sort
bekommt, wie meine int-string
Paare sortieren? Wie mache ich das für eine Klasse von mir als Paar first
? Gibt es eine Möglichkeit, nach second
mit std::sort
zu sortieren?
'std :: pair' hat einen' Operator <'. Wenn Sie möchten, dass 'std :: sort' anders sortiert, geben Sie ihm einen Komparator. – chris
http://en.cppreference.com/w/cpp/utility/pair/operator_cmp – bolov
Sie können versuchen, eine Spezialisierung für den Bool-Operator<(const & std :: pair op1, const & std :: pair op2) 'Funktion, und übergeben Sie dies zum Sortieren. –