001
31.01.2004, 20:50 Uhr
virtual
Sexiest Bit alive (Operator)
|
Im Prinzip musst Du dem sort einfach nur eine Funktion als dritten parameter übergeben, die in Deinem Fall folgende Signatur haben sollte:
| C++: |
bool dein_less(const ARTIKEL& a, const ARTIKEL& b) { ... // Gebe true zurück, wenn a<b }
|
Ich habe das mal anhand eines einfachen String arrays gemacht, wobei das alternative Sortierkriterium ist, die Strings rückwärts zu vergleichen:
| C++: |
#include <algorithm> #include <iostream> #include <iterator> #include <string>
bool custom_less(const std::string& a, const std::string& b) { std::string::const_reverse_iterator ra = a.rbegin(); std::string::const_reverse_iterator rb = b.rbegin();
while (ra!=a.rend() && rb!=b.rend()) { int diff = int(*rb++) - int(*ra++); if (diff<0) return false; if (diff>0) return true; } return ra!=a.rend() || rb==b.rend(); }
int main() { std::string array[] = { "mike", "windalf", "0xdeadbeef", "ao", "virtual" };
/* Zur erinnerung, wie es normal geht */ // Normale Sortierung std::sort(array, array+sizeof(array)/sizeof(*array)); // Ausgabe std::copy(array, array+sizeof(array)/sizeof(*array), std::ostream_iterator<std::string>(std::cout, "\n")); std::cout<<std::endl;
/* Jetzt wird interessant für mike */ // Custom sort std::sort(array, array+sizeof(array)/sizeof(*array), custom_less); // Ausgabe std::copy(array, array+sizeof(array)/sizeof(*array), std::ostream_iterator<std::string>(std::cout, "\n")); }
|
-- Gruß, virtual Quote of the Month Ich eß' nur was ein Gesicht hat (Creme 21) Dieser Post wurde am 31.01.2004 um 20:51 Uhr von virtual editiert. |